Regex 正则表达式:为什么是a??模式匹配空字符串“&引用;来自任何字符串,包括;a「;它本身

Regex 正则表达式:为什么是a??模式匹配空字符串“&引用;来自任何字符串,包括;a「;它本身,regex,Regex,从中我了解了“正则表达式-量词”,并在此基础上在本教程中使用 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. 及 也 为什么?这是因为您正在使用?运算符惰性处理?,因此它将尽可能少地匹配

从中我了解了“正则表达式-量词”,并在此基础上在本教程中使用

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.


为什么?

这是因为您正在使用
运算符惰性处理
,因此它将尽可能少地匹配


您试图将
a
0或1次匹配,但您告诉正则表达式引擎要尽可能少地匹配,这样它将匹配0次,并匹配字符串(+1)中尽可能多的字符。

这是因为您正在使用
操作符惰性地匹配
,所以它将尽可能少地匹配


您试图将
a
0或1次匹配,但您告诉正则表达式引擎尽可能少地匹配,这样它将匹配0次,并匹配字符串(+1)中尽可能多的字符。

是一个量词,因此它表示量化项应匹配多少次,0或1次,最好是0<代码>??本身不匹配任何内容,它只是修饰另一个表达式,表示该表达式在测试字符串中要匹配多少次

Iff表达式的其余部分与
0次
部分匹配不匹配,它将使用
1次
部分匹配重试

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


不过,为什么正则表达式对字符串中的每个字符都匹配一次(加上末尾的一个字符)?空匹配是一个有效的正则表达式。例如,搜索
^
$
(字符串的开头和结尾)将生成一个匹配项,尽管是空的。对于这个“无用”表达式也是一样的,测试字符串中的每个位置都是表达式的有效匹配,而表达式不会对匹配施加任何约束。

是一个量词,因此它表示量化项应该匹配多少次,0或1次,最好是0<代码>??本身不匹配任何内容,它只是修饰另一个表达式,表示该表达式在测试字符串中要匹配多少次

Iff表达式的其余部分与
0次
部分匹配不匹配,它将使用
1次
部分匹配重试

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


不过,为什么正则表达式对字符串中的每个字符都匹配一次(加上末尾的一个字符)?空匹配是一个有效的正则表达式。例如,搜索
^
$
(字符串的开头和结尾)将生成一个匹配项,尽管是空的。对于这个“无用”表达式也是一样,被测试字符串中的每个位置都是表达式的有效匹配,并且没有对匹配施加任何约束。

是否确实存在
匹配任何内容的情况?事实上,我昨天读过它,我认为它不会匹配。这只是一个普通的量词,量词本身会使它们变懒。实际上有没有任何情况下,
匹配任何东西?事实上,我昨天读了它,我认为它不会匹配。它只是一个通用的量词,量词本身会使它们变得懒惰。
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.
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.