为什么re.findall()找到比re.sub()更多的匹配?

Tim*_*ker 16 python regex

考虑以下:

>>> import re
>>> a = "first:second"
>>> re.findall("[^:]*", a)
['first', '', 'second', '']
>>> re.sub("[^:]*", r"(\g<0>)", a)
'(first):(second)'
Run Code Online (Sandbox Code Playgroud)

re.sub()最初的行为更有意义,但我也能理解re.findall()行为.毕竟,你可以匹配之间的空字符串 first:仅包含非冒号字符(其中恰好为零),但为什么不re.sub()表现的一样吗?

不应该是最后一个命令的结果(first)():(second)()吗?

Cas*_*yte 9

你使用允许空匹配的*:

'first'   -> matched
':'       -> not in the character class but, as the pattern can be empty due 
             to the *, an empty string is matched -->''
'second'  -> matched
'$'       -> can contain an empty string before,
             an empty string is matched -->''
Run Code Online (Sandbox Code Playgroud)

引用文档re.findall():

结果中包含空匹配,除非它们触及另一个匹配的开头.

您在子结果中看不到空匹配的原因在以下文档中说明re.sub():

仅当与前一个匹配不相邻时,才会替换模式的空匹配.

试试这个:

re.sub('(?:Choucroute garnie)*', '#', 'ornithorynque') 
Run Code Online (Sandbox Code Playgroud)

现在这个:

print re.sub('(?:nithorynque)*', '#', 'ornithorynque')
Run Code Online (Sandbox Code Playgroud)

没有连续的#