Python RE - finditer 和 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”)。
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, whereas finditer()
matches the whole pattern.
Why is that happening?
(I defined my pattern p
as I did in order to allow capturing patterns that contain repeated sequences of [CC]s such as 'look [CC] [CC] on' in s2).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
i.group()
返回整个匹配项,包括组之前和之后的非空白字符。要获得与findall
示例相同的结果,请使用i.group(1)
http://docs.python.org/library/re.html#re.MatchObject.group
i.group()
returns the whole match, including the non-whitespace characters before and after your group. To get the same result as in yourfindall
example, usei.group(1)
http://docs.python.org/library/re.html#re.MatchObject.group