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')。
1 个回答
1
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] '