简体   繁体   中英

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.

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).

Thanks

i.group() returns the whole match, including the non-whitespace characters before and after your group. To get the same result as in your findall example, use 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] '

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM