在该页的末尾,尝试解释了贪婪、不情愿和占有量词如何工作:http://docs.oracle.com/javase/tutorial/essential/regex/quant.html http://docs.oracle.com/javase/tutorial/essential/regex/quant.html
然而我自己尝试了一个例子,但我似乎并没有完全理解它。
我直接贴出我的结果:
Enter your regex: .*+foo
Enter input string to search: xfooxxxxxxfoo
No match found.
Enter your regex: (.*)+foo
Enter input string to search: xfooxxxxxxfoo
I found the text "xfooxxxxxxfoo" starting at index 0 and ending at index 13.
为什么第一个 reg.exp.找不到匹配项,第二个找到匹配项吗?
这两个 reg.exp. 之间的确切区别是什么?
The +
另一个量词之后的意思是“不允许正则表达式引擎回溯到前一个标记已匹配的任何内容”。 (参见教程所有格量词 http://www.regular-expressions.info/possessive.html here).
所以当你申请的时候.*foo
to "xfooxxxxxxfoo"
, the .*
首先匹配整个字符串。然后,自从foo
无法匹配,正则表达式引擎会回溯,直到可以匹配为止,在以下情况下实现匹配.*
已匹配"xfooxxxxxx"
and foo
已匹配"foo"
.
现在额外的+
防止回溯发生,因此匹配失败。
当你写的时候(.*)+foo
. the +
呈现出完全不同的含义;现在它的意思是“一个或多个前面的标记”。顺便说一句,您已经创建了嵌套量词,这不是一个好主意。如果您将该正则表达式应用于类似的字符串"xfoxxxxxxxxxfox"
,你会遇到灾难性的回溯 http://www.regular-expressions.info/catastrophic.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)