Which would be better non-greedy regex or negated character class?

前端 未结 2 1505
离开以前
离开以前 2020-12-19 15:52

I need to match @anything_here@ from a string @anything_here@dhhhd@shdjhjs@. So I\'d used following regex.

^@.*?@

2条回答
  •  情话喂你
    2020-12-19 16:45

    It is clear the ^@[^@]*@ option is much better.

    The negated character class is quantified greedily which means the regex engine grabs 0 or more chars other than @ right away, as many as possible. See this regex demo and matching:

    When you use a lazy dot matching pattern, the engine matches @, then tries to match the trailing @ (skipping the .*?). It does not find the @ at Index 1, so the .*? matches the a char. This .*? pattern expands as many times as there are chars other than @ up to the first @.

    See the lazy dot matching based pattern demo here and here is the matching steps:

提交回复
热议问题