Reputation: 904
I did the following:
a = re.compile("(ab*?)")
b = a.search("abbbbbbb")
The following gave me the answer 'a':
b.group(0)
Surprisingly, this also gave me the answer 'a':
b.group(1)
I get a tuple containing only ('a',) when I do this:
b.groups()
If there is only one group, why did it give repeated values for indices 0 and 1? Shouldn't it have raised an IndexError at 1?
Upvotes: 0
Views: 40
Reputation: 148
help(b.group)
Help on built-in function group:
group(...) method of _sre.SRE_Match instance
group([group1, ...]) -> str or tuple.
Return subgroup(s) of the match by indices or names.
For 0 returns the entire match.
Regular expressions start numbering the capture groups at 1. Trying to access group 0 will give you the entire match (all groups), but since the expression has only one group the outputs are the same.
Example:
>>> regex = re.compile("(first) (second)")
>>> results = regex.search("first second")
>>> results.group(1)
'first'
>>> results.group(2)
'second'
>>> results.group(0)
'first second'
Upvotes: 2