为什么 Python findall() 和 finditer() 在未锚定的 .* 搜索中返回空匹配? [英] Why do Python findall() and finditer() return empty matches on unanchored .* searches?
本文介绍了为什么 Python findall() 和 finditer() 在未锚定的 .* 搜索中返回空匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
findall()
和 finditer()
的 Python 文档声明:
The Python docs for findall()
and finditer()
state that:
空匹配项包含在结果中,除非它们触及另一场比赛开始
Empty matches are included in the result unless they touch the beginning of another match
这可以证明如下:
In [20]: [m.span() for m in re.finditer('.*', 'test')]
Out[20]: [(0, 4), (4, 4)]
谁能告诉我,为什么这个模式首先返回一个空匹配?.*
不应该消耗整个字符串并返回单个匹配项吗?此外,如果我将模式锚定到字符串的开头,为什么最后没有空匹配?例如
Can anyone tell me though, why this pattern returns an empty match in the first place? Shouldn't .*
consume the entire string and return a single match? And further, why is there no empty match at the end if I anchor the pattern to the beginning of the string? e.g.
In [22]: [m.span() for m in re.finditer('^.*', 'test')]
Out[22]: [(0, 4)]
推荐答案
.*
是零个或多个,所以一旦消耗了四个字符,末尾的零长度空字符串(不触及开头的任何匹配)仍然存在;和- 末尾的空字符串与模式不匹配 - 它不在字符串的开头.
.*
is zero or more, so once the four characters are consumed, the zero-length empty string at the end (which doesn't touch the start of any match) still remains; and- The empty string at the end doesn't match the pattern - it doesn't start at the start of the string.
这篇关于为什么 Python findall() 和 finditer() 在未锚定的 .* 搜索中返回空匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文