I am not able to understand the following code behavior.
>>> import re
>>> text = 'been'
>>> r = re.compile(r'b(e)*')
>>> r.search(text).group()
'bee' #makes sense
>>> r.findall(text)
['e'] #makes no sense
I read some already existing question and answers about capturing groups and all. But still I am confused. Could someone please explain me.
When a pattern contains a capture group,
findall
returns only the content of the capture group and no more the whole match.If this behaviour looks strange, it can be very useful to extract easily parts of a string in a particular context (substring before or after), especially since python re module doesn't support variable length lookbehinds.
The answer is simplified in the Regex Howto
As you can read here,
group
returns the string matched by the Regular Expression.But the action of
findall
is justified in the documentationSo you are getting the matched part of the capture group.
Some experiments include :
Here the regex has two capturing groups, so the returned values are a list of matched groups (in tuples)