我正在学习 Java教程中的量词。
其中提到了贪婪、勉强和占有量词之间的差异。
我无法确切地理解它们之间的区别。
如下所示的解释:
Enter your regex: .*foo // greedy quantifier
Enter input string to search: xfooxxxxxxfoo
I found the text "xfooxxxxxxfoo" starting at index 0 and ending at index 13.
Enter your regex: .*?foo // reluctant quantifier
Enter input string to search: xfooxxxxxxfoo
I found the text "xfoo" starting at index 0 and ending at index 4.
I found the text "xxxxxxfoo" starting at index 4 and ending at index 13.
Enter your regex: .*+foo // possessive quantifier
Enter input string to search: xfooxxxxxxfoo
No match found.
第一个示例使用贪婪量词 .* 查找"任何内容",零次或多次,并跟随字母"f""o""o"。由于量词是贪婪的,表达式中的 .* 部分首先会占用整个输入字符串。此时,整个表达式无法成功,因为最后三个字母("f""o""o")已被消耗。因此,匹配器逐个字母地缓慢后退,直到右侧出现的 "foo" 被反推出来,此时匹配成功并结束搜索。然而,第二个示例是勉强的,因此它首先将“nothing”消耗掉。由于“foo”不出现在字符串的开头,它被迫吞下第一个字母(一个“x”),这触发了0和4处的第一次匹配。我们的测试工具继续进行该过程,直到输入字符串用尽。它在4和13处找到另一个匹配项。
第三个示例未能找到匹配项,因为量词是独占的。在这种情况下,.*+ 会消耗整个输入字符串,没有留下任何内容来满足表达式末尾的 "foo"。在想要占用所有内容而永远不回退的情况下,请使用独占量词;在没有立即找到匹配项的情况下,它将优于相应的贪婪量词。