Skip to main content
 首页 » 编程设计

Python RE之finditer 和 findall 的不同匹配

2025年05月04日11mq0036

这是一些代码:

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