理解所有格量词,java regex [英] Understanding possessive quantifiers, java regex
问题描述
我知道占有正则表达式会转到文本的末尾,并且不会回溯以查看结尾之前是否有匹配项.如果最后有匹配项,则返回 true,否则立即返回 false.我已经试过了:
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 (i.e. *? or *+). Is that right? Thanks!
推荐答案
即使最后有一场比赛,它也没有给我任何东西.任何想法为什么?
It gives me nothing even though there's a match in the end. Any ideas why?
.*+
将匹配整个输入字符串(包括最后一个 foo
).并且因为它不会从字符串的末尾回溯,所以正则表达式 .*+foo
不匹配.
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.
因此,正则表达式 .*?foo
将匹配 "xxfoo"
而正则表达式 .*foo
将匹配 "xxfooxxxxxfooxxxfoo"
.
So, the regex .*?foo
would match "xxfoo"
and the regex .*foo
would match "xxfooxxxxxfooxxxfoo"
.
这篇关于理解所有格量词,java regex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!