簡體   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