0

From this tutorial I learned about "Regular Expressions - Quantifiers", and based on this test code used in this tutorial.

Enter your regex: a??
Enter input string to search: a
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.

And

Enter your regex: a??
Enter input string to search: aaa
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.

Also

Enter your regex: a??
Enter input string to search: cab
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.

Why?

4

2 回答 2

4

??是一个量词,所以它表示量化项应该匹配多少次,0 或 1 次,最好是 0??它本身不匹配任何东西,它只是装饰另一个表达式,说明该表达式在测试字符串中要匹配多少次。

如果表达式的其余部分与惰性 0 times部分匹配不匹配,它将再次尝试1 time部分匹配。

确实,如果整个正则表达式仅包含某个术语的惰性可选匹配,它将始终匹配测试字符串中的空位置。所以这种量词只有在它周围有其他术语时才有用。例如,表达式ba??d将首先尝试匹配bd,然后bad.

不过,为什么正则表达式匹配字符串中的每个字符一次(最后加一个)?好吧,一个空匹配是一个有效的正则表达式。例如,搜索^or $(字符串的开始,分别结束)将产生一个匹配,尽管它是空的。对于这个“无用”的表达式也是如此,测试字符串中的每个位置都是表达式的有效匹配,不会对匹配施加任何约束。

于 2013-01-08T08:19:54.087 回答
0

这是因为您正在使用?LAZY 操作符,?所以它会尽可能少地匹配。

您正在尝试匹配a0 或 1 次,但您告诉正则表达式引擎尽可能少地匹配,以便匹配 0 次并且匹配字符串中的尽可能多的字符 (+1)。

于 2013-01-08T08:02:26.037 回答