-edit- NOTE the ?
at the end of .{2,}?
I found out you can write
.{2,}?
Isnt that exactly the same as bel
What makes this question especially interesting is that there are times when .{2,}?
is equivalent to .{2}
, but it should never happen. Others have already pointed out how a reluctant quantifier at the very end of a regex always matches the minimum number of of characters because there's nothing after it to force it to consume more.
The other place they shouldn't be used is at the end of a subexpression inside an atomic group. For example, suppose you try to match foo bar
with
f(?>.+?) bar
The subexpression initially consumes the first 'o' and hands off to the next part, which tries unsuccessfully to match a space. Without the atomic group, it would backtrack and let the .+?
consume another character. But it can't backtrack into the atomic group, and there's no wiggle room before the group, so the match attempt fails.
A reluctant quantifier at the end of a regex or at end of an atomic subexpression is definite code smell.