Example for java regex X?? ,X?+ and X?
This question already has an answer here:
这是我喜欢想到的方式 -
X?? Negative bias, 0 or 1 time - preference to 0 if possible
X? Neutral bias, 0 or 1 time
X?+ Positive bias, 0 or 1 time - preference to 1 if possible,
and if 1 won't give it up (backtrack)
You need more complex patterns to see the difference.
A greedy quantifier first matches as much as possible (but backtracks).
A reluctant or "non-greedy" quantifier first matches as little as possible.
A possessive quantifier is just like the greedy quantifier, but it doesn't backtrack.
Use capturing groups to see what is happening.
Try patterns such as (b?)(b+)
, (b??)(b+)
, (b?+)(b+)
on the strings b
and bb
.
Print A) if it matches, and B) if so, what are the groups?
The following is what I would expect, but did not test:
Greedy: it should match on empty and b
in the first case (by backtracking!), b
, b
in the second.
Reluctant: it should match on , `b` in the first case,
, bb
in the second. The first group will actually never match anything, so this pattern does not make sense.
Possessive: it should NOT match the first (no more b
left for second group, and it doesn't backtrack) and b
, b
in the second string (no backtracking needed).
Take a look at these examples
System.out.println("abb".matches("abb?b")); // Greedy -> true
System.out.println("abb".matches("abb??b")); // Reluctant -> true
System.out.println("abb".matches("abb?+b")); // Possessive -> false
Firs two will match because even if ?
will be greedy or reluctant ??
second b
can be returned and used to match variant of regex where this part wasn't found.
Interesting thing happens in ?+
which is possessive so when it match something then it means that this part belongs to possessive part of regex, and cant be matched by rest of regex. So because second b
is matched by b?+
it cant be matched by last b
regex, that is why matches
returns false
.