简体   繁体   中英

Java regex possesive quantifiers

Given this regex:

x[^x]*+x

and this input string for matching:

xbbbx

The result is the matched text xbbbx starting at index 0 and ending at index 5.

But, by only changing the last letter x to Z in both the regex and the string, we get this regex:

x[^x]*+Z

and this input string:

xbbbZ

and the result is: no match found .

Why would a change in a single letter produce this change in behavior?

The reason why is you are using the "possessive" quantifier which will match the symbol as much as it can.

So in this case with xbbbZ the regex x[^x]*+ matches all non x characters until the end of the line, where it stops. It has already consumed the "Z" inside of the input xbbbZ .

This regex, x[^x]*+x , works with xbbbx because the "possessive" quantifier has to stop when it reaches an x . Your input has an x at the end, and therefore the possessive quantifier stops. This allows the last part of the regex x to be matched with x .

At the end of the Java tutorial page , you can see another example of the possessive quantifier.

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