Search code examples
pythonregexfindall

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


Solution

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