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.

链接地址: http://www.djcxy.com/p/76994.html

上一篇: 正则表达式只匹配第一个子字符串

下一篇: Java正则表达式拥有量词