Reputation: 3530
I understand .*
(greedy quantifier) backtracks and tries to find a match. and .*+
(possessive quantifier) does not backtrack.
However I have been using .*
and .\*?
frequently but don't know when to use .*+
.
Can somebody give a situation or an example where .*+
should be used?
explanation with an example is appreciated.
EDIT:
i have gone through the theory part and i repeat i understand how it works. i just need one example that matches possessive quantifiers (.*+
)
Upvotes: 4
Views: 988
Reputation: 4758
There are many (regex dependent) implementation details so it's difficult to generalize these things. For example with ^.*.+
you get a match on the string " "
. With ^.*+.+
you don't. Because the first matcher already swallowed the whole string of whitespace.
You can use it in any case where you don't want the next part of your regex to accidentally match a part of the preceding.
You can test this with PCRE settings at https://regex101.com/
Upvotes: 2
Reputation: 20863
Note that if a possessive patter matches, then so will the greedy pattern. The converse is not true. Therefore you can use a possessive quantifier if you want to limit your matches to a smaller set.
Secondly possessive quantifiers are useful when the input string does not match your pattern. Since they "eat" their input and don't backtrack they will be faster in detecting a non-match. In extreme cases this is called catastrophic backtracking and has brought down sites (including StackOverflow, see here).
Upvotes: 1