What's the difference between these RegEx

前端 未结 3 1594
温柔的废话
温柔的废话 2020-12-10 23:07
  1. (\\d+|) vs (\\d+)?
  2. [\\w\\W] vs [\\d\\D] vs .

Is there any difference between t

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-10 23:56

    You didn't say which language you're using, so I'm going to assume Perl.

    1. (\d+|) is equivalent to (\d*). It matches a sequence of 0 or more digits and captures the result into $1. (\d)? matches 0 or 1 digit. If it matches a digit, it puts it in $1; otherwise $1 will be undef (you could rewrite it as (?:(\d)|) if you want to eliminate the ?).

    2. [\w\W] and [\d\D] are equivalent, matching any character. . is equivalent to [^\n] by default (matching any character but newline). If you really want to match any character, you should use . and specify the /s flag, which makes . match any character.

提交回复
热议问题