0
Enter your regex: a?
Enter input string to search: ababaaaab
I found the text "a" starting at index 0 and ending at index 1.
I found the text "" starting at index 1 and ending at index 1.
I found the text "a" starting at index 2 and ending at index 3.
I found the text "" starting at index 3 and ending at index 3.
I found the text "a" starting at index 4 and ending at index 5.
I found the text "a" starting at index 5 and ending at index 6.
I found the text "a" starting at index 6 and ending at index 7.
I found the text "a" starting at index 7 and ending at index 8.
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.

Enter your regex: a*
Enter input string to search: ababaaaab
I found the text "a" starting at index 0 and ending at index 1.
I found the text "" starting at index 1 and ending at index 1.
I found the text "a" starting at index 2 and ending at index 3.
I found the text "" starting at index 3 and ending at index 3.
I found the text "aaaa" starting at index 4 and ending at index 8.
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.

Enter your regex: a+
Enter input string to search: ababaaaab
I found the text "a" starting at index 0 and ending at index 1.
I found the text "a" starting at index 2 and ending at index 3.
I found the text "aaaa" starting at index 4 and ending at index 8.  



上面的例子来自Java Documentation于量词。
根据我从上面给出的示例中了解到的情况,以下是贪婪量词的工作原理:

? 和 *

将寻找提到的字符的存在。如果未找到它们前面的字符,则将该位置标记为零长度匹配。
*一个字符一个字符的匹配,而?一个组。

+

+将进行正则表达式的逐组匹配。它不会进行零长度匹配。

我的问题是:
我对量词的理解是正确的还是我搞砸了?
此外,是否有任何对大脑友好的 Java 正则表达式指南(Google 上没有针对初学者的可用指南)?

4

3 回答 3

1

是的,你的理解是正确的。

如需指南,只需查找正则表达式;除了函数调用和其他什么之外,Java 没有什么太具体的东西。例如,1 秒搜索导致http://www.aivosto.com/vbtips/regex.html

编辑:Explosion Pills 指向http://www.regular-expressions.info/这是一个很好的来源。它有一个特定于 Java 的部分,但当然模式本身仍然是标准的正则表达式语法。

于 2013-02-18T01:51:28.797 回答
1
  • 一个字符一个字符的匹配,而 ? 去一个团体。

*匹配零个或多个。 ?匹配零或 1。

这些都与群体或角色无关。正则表达式中的“组”或“捕获组”是带括号的元素,可以通过该方法单独提取java.util.regex.Matcher.group

(foo)*匹配"", "foo""foofoo"所以显然正文不需要是单个字符。

(foo)?匹配""and"foo"但不是"foofoo".

  • 将进行正则表达式的逐组匹配。它不会进行零长度匹配。

No. +与 body 匹配一次或多次,因此x*相当于(?:x+)?+操作员可以很好地执行零长度匹配 。()+匹配空字符串。

于 2013-02-18T02:19:12.610 回答
0

我的理解是,?如果字符出现 0 次或 1 次*则匹配,如果出现任意次数(包括 0)+则匹配,如果至少出现一次则匹配。

于 2013-02-18T01:54:29.960 回答