How does the group in regular expression work when there is only one group?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



How does the group in regular expression work when there is only one group?



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?





Not sure how this is possible, considering the documentation for group() states If a group number is negative or larger than the number of groups defined in the pattern, an IndexError exception is raised.
– Easton Bornemeier
Aug 8 at 17:57


group()


If a group number is negative or larger than the number of groups defined in the pattern, an IndexError exception is raised.





Why don't you try it and see it for yourself?
– Mithil Bhoras
Aug 8 at 17:59




1 Answer
1



help(b.group)


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'





Could you give one example to elaborate?
– Mithil Bhoras
Aug 8 at 18:03





@MithilBhoras I added an example to my answer
– hbgoddard
Aug 8 at 18:07





Thanks a ton!!!
– Mithil Bhoras
Aug 8 at 18:08






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS