简体   繁体   English

Python RE-finditer和findall的不同匹配

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

here is some code: 这是一些代码:

>>> 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'

Obviously, this is more relevant for finding all matches in s3 in which findall returns: ['[CC] ', '[CC] '], as it seems that findall only matches the inner group in p while finditer matches the whole pattern. 显然,这与在s3中查找findall返回的所有匹配项更为相关:['[CC]','[CC]'],因为似乎findall仅匹配p中的内部组,而finditer匹配整个模式。

Why is that happening? 为什么会这样呢?

(I defined p as i did in order to allow capturing patterns that contain sequences of [CC]s such as 'look [CC] [CC] on' in s2). (我定义了p就是为了允许捕获包含[CC]序列的模式,例如s2中的'look [CC] [CC] on')。

Thanks 谢谢

i.group() returns the whole match, including the non-whitespace characters before and after your group. i.group()返回整个匹配项,包括组前后的非空白字符。 To get the same result as in your findall example, use i.group(1) 要获得与findall示例相同的结果,请使用i.group(1)

http://docs.python.org/library/re.html#re.MatchObject.group 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