Greedy vs. Reluctant vs. Possessive Qualifiers

I’ll give it a shot.

A greedy quantifier first matches as much as possible. So the .* matches the entire string. Then the matcher tries to match the f following, but there are no characters left. So it “backtracks”, making the greedy quantifier match one less character (leaving the “o” at the end of the string unmatched). That still doesn’t match the f in the regex, so it backtracks one more step, making the greedy quantifier match one less character again (leaving the “oo” at the end of the string unmatched). That still doesn’t match the f in the regex, so it backtracks one more step (leaving the “foo” at the end of the string unmatched). Now, the matcher finally matches the f in the regex, and the o and the next o are matched too. Success!

A reluctant or “non-greedy” quantifier first matches as little as possible. So the .* matches nothing at first, leaving the entire string unmatched. Then the matcher tries to match the f following, but the unmatched portion of the string starts with “x” so that doesn’t work. So the matcher backtracks, making the non-greedy quantifier match one more character (now it matches the “x”, leaving “fooxxxxxxfoo” unmatched). Then it tries to match the f, which succeeds, and the o and the next o in the regex match too. Success!

In your example, it then starts the process over with the remaining unmatched portion of the string, “xxxxxxfoo”, following the same process.

A possessive quantifier is just like the greedy quantifier, but it doesn’t backtrack. So it starts out with .* matching the entire string, leaving nothing unmatched. Then there is nothing left for it to match with the f in the regex. Since the possessive quantifier doesn’t backtrack, the match fails there.

Leave a Comment