Python regular expression findall *

2020-05-10 04:28发布

问题:

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.

回答1:

The answer is simplified in the Regex Howto

As you can read here, group returns the string matched by the Regular Expression.

group() returns the substring that was matched by the RE.

But the action of findall is justified in the documentation

If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group

So you are getting the matched part of the capture group.

Some experiments include :

>>> r = re.compile(r'(b)(e)*')
>>> r.findall(text)
[('b', 'e')]

Here the regex has two capturing groups, so the returned values are a list of matched groups (in tuples)



回答2:

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.