3
votes

I was looking at this question Greedy vs. Reluctant vs. Possessive Quantifiers

I can see how *+ and * both match zero or more times, but the possessive quantifier *+ will match forwards as much as possible.. And the * will do .* and backtrack. And I can accept that *+ would be more efficient when the .* string is long.

I'm interested in when they give different results though.

And I saw a comment

@moodboom, there are zero cases ever (mathematical fact) where possessive quantifiers will produce a match that will not be produced by simple greedy quantifiers. There are occasional cases where they will produce a no match when greedy quantifiers would produce a match. For ALL other cases (where greedy and possessive produce the same results), possessive quantifiers give a performance gain. – Wildcard May 5 at 23:00

I'd be very interested to see this expanded upon, specific cases where possessive and greedy quantifiers give a different result.

Contrasting *+ and *

I'd also be interested in the case of what different results are possible, contrasting ?+ vs ?

2
Hmmm, I meant to answer this but didn't get around to it. On mobile now but may be able to do so tomorrow. - Wildcard
@Wildcard thanks. whenever you have time is fine - barlop
Very related (with an example of the different matches, and with many beautiful explanations of the intricacies in the answers): stackoverflow.com/questions/5319840/… - Dewi Morgan
@DewiMorgan I mention that one in the first line, that is useful as a foundation to help understand this question but that question is quite general and the answers there don't cover this question. - barlop

2 Answers

2
votes

I found a case, yet I'm not certain about the explanation and pertinence. And I think there are many other cases.

Test case

greedy = /.*b/
posssessive = /.*+b/

Tested on:

foob

Only greedy matches it.

Explanation

Possessive will first match the whole string (.*+) and then try to match b char but find only end of string ($).

Greedy will also match the whole string, but then look backward until it finds a first b char. Which it will find.

0
votes

check out the examples in the demo for test strings aaab and aaax try the greedy pattern a*[^b] and the possessive pattern a*+[^b]

Demo 1

Demo 2

a*[^b] will backtrack to try to find a match hence it finds aaa in aaab

a*+[^b] will find aaa will not backtrack and will try to match [^b], fails on aaab