Possessive quantifiers

Possessive quantifiers are quantifiers that are greedy when matching text like greedy quantifiers do. Both greedy and possessive quantifiers try to match as many characters as possible. The important difference, however, is that the possessive quantifiers do not backtrack (go back) unlike greedy quantifiers; therefore, it is possible that the regex match fails if the possessive quantifiers go too far.

This table shows all the three types of quantifiers, side by side:

Greedy Quantifier Lazy Quantifier Possessive Quantifier
m* m*? m*+
m+ m+? m++
m? m?? m?+
m{X} m{X}? m{X}+
m{X,} m{X,}? m{X,}+
m{X,Y} m{X,Y}? m{X,Y}+


Let's take an example input string, a1b5, and see the behavior of the greedy, lazy, ...

Get Java 9 Regular Expressions now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.