简体   繁体   中英

Understanding possessive quantifiers, java regex

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 gives 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 (ie *? 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 (ie *? 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 (eg, [^f]*+.*foo or, if you know that the only "f" characters will be at the start of "foo", [^f]*+foo ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM