I understand that a possesive regex would go to the end of the text and would not backtrack to see if there was a match before the end. If at the end there's a match it returns true, otherwise it immidiatly returns false. I've tride this:
Pattern patt = Pattern.compile(".*+foo");
Matcher matcher = patt.matcher("xxfooxxxxxfooxxxfoo");
while (matcher.find())
System.out.println(matcher.group());
It giv开发者_JAVA百科es me nothing even though there's a match in the end. Any ideas why?
Also I understand that to make a regex lazy/possessive I add ?/+ after the first quantifier (i.e. *? or *+). Is that right? Thanks!
It gives me nothing even though there's a match in the end. Any ideas why?
The .*+
will match the entire input string (including the last foo
). And because it does not backtrack from the end of the string, the regex .*+foo
does not match.
Also I understand that to make a regex lazy/possessive I add ?/+ after the first quantifier (i.e. *? or *+). Is that right?
The counter part of possessive is not lazy. That would be greedy, which *
by default is.
So, the regex .*?foo
would match "xxfoo"
and the regex .*foo
would match "xxfooxxxxxfooxxxfoo"
.
Possessive quantifiers will not give up matches on a backtrack. The .*+
matches your entire string and then there's nothing for foo
to match.
Er, like Bart said. :)
Use possessive quantifiers only when you know that what you've matched should never be backtracked (e.g., [^f]*+.*foo
or, if you know that the only "f" characters will be at the start of "foo", [^f]*+foo
).
精彩评论