繁体   English   中英

Python RE-finditer和findall的不同匹配

[英]Python RE - different matching for finditer and findall

这是一些代码:

>>> p = re.compile(r'\S+ (\[CC\] )+\S+')
>>> s1 = 'always look [CC] on the bright side'
>>> s2 = 'always look [CC] [CC] on the bright side'
>>> s3 = 'always look [CC] on the [CC] bright side'
>>> m1 = p.search(s1)
>>> m1.group()
'look [CC] on'
>>> p.findall(s1)
['[CC] ']
>>> itr = p.finditer(s1)
>>> for i in itr:
...     i.group()
... 
'look [CC] on'

显然,这与在s3中查找findall返回的所有匹配项更为相关:['[CC]','[CC]'],因为似乎findall仅匹配p中的内部组,而finditer匹配整个模式。

为什么会这样呢?

(我定义了p就是为了允许捕获包含[CC]序列的模式,例如s2中的'look [CC] [CC] on')。

谢谢

i.group()返回整个匹配项,包括组前后的非空白字符。 要获得与findall示例相同的结果,请使用i.group(1)

http://docs.python.org/library/re.html#re.MatchObject.group

In [4]: for i in p.finditer(s1):
...:     i.group(1)
...:     
...:     
Out[4]: '[CC] '

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM