【发布时间】:2014-06-21 21:37:07
【问题描述】:
我在Oracle的教程中练习java的正则表达式。为了更好地理解贪婪、不情愿和所有格量词,我创建了一些示例。我的问题是这些量词在捕获组时如何工作。我不明白以这种方式使用量词,例如,勉强的量词看起来好像根本不起作用。另外,我在互联网上搜索了很多,只看到了像 (.*?) 这样的表达式。为什么人们通常使用具有这种语法的量词而不是 "(.foo)??" 之类的东西,有什么原因吗?
这是不情愿的例子:
Enter your regex: (.foo)??
Enter input string to search: xfooxxxxxxfoo
I found the text "" starting at index 0 and ending at index 0.
I found the text "" starting at index 1 and ending at index 1.
I found the text "" starting at index 2 and ending at index 2.
I found the text "" starting at index 3 and ending at index 3.
I found the text "" starting at index 4 and ending at index 4.
I found the text "" starting at index 5 and ending at index 5.
I found the text "" starting at index 6 and ending at index 6.
I found the text "" starting at index 7 and ending at index 7.
I found the text "" starting at index 8 and ending at index 8.
I found the text "" starting at index 9 and ending at index 9.
I found the text "" starting at index 10 and ending at index 10.
I found the text "" starting at index 11 and ending at index 11.
I found the text "" starting at index 12 and ending at index 12.
I found the text "" starting at index 13 and ending at index 13.
对于不情愿,它不应该为索引 0 和 4 显示“xfoo”吗?这里是所有格:
Enter your regex: (.foo)?+
Enter input string to search: afooxxxxxxfoo
I found the text "afoo" starting at index 0 and ending at index 4
I found the text "" starting at index 4 and ending at index 4.
I found the text "" starting at index 5 and ending at index 5.
I found the text "" starting at index 6 and ending at index 6.
I found the text "" starting at index 7 and ending at index 7.
I found the text "" starting at index 8 and ending at index 8.
I found the text "xfoo" starting at index 9 and ending at index 13.
I found the text "" starting at index 13 and ending at index 13.
对于所有格,它不应该只尝试一次输入吗?我真的很困惑,尤其是这个,因为尝试了每一种可能性。
提前致谢!
【问题讨论】:
-
检查quantifiers下的SO regex reference,它将链接到this question