views:

30

answers:

1

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

A: 

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] '
piquadrat
I'm not sure I understand. findall() returns a list of matching strings. How can i use group(1) on its output?
ScienceFriction
No, you use group on the elements in the iterator returned from `p.finditer(s1)`. I added an example in my answer.
piquadrat
ah, thanks. I know how to use the group(1) with the iterator. the thing is that I want the same result as in finditer - i do want to get the whole pattern. I don't understand how come findall doesn't return the full pattern.
ScienceFriction
That's documented behavior: "If one or more groups are present in the pattern, return a list of groups", http://docs.python.org/library/re.html#re.findall
piquadrat
thanks. I didn't notice this. It basically means that I have to define the whole pattern as an outer group: p = re.compile(r'(\S+ (\[CC\] )+\S+)') and then use only the first element in each tuple in the returned list of tuples. Or simply use finditer() :)
ScienceFriction