re.MatchObject.group() function in Python Regex
re.MatchObject.group() method returns the complete matched subgroup by default or a tuple of matched subgroups depending on the number of arguments
- group: (optional) group defaults to zero (meaning that it it will return the complete matched string). Return -1 if group exists but did not contribute to the match.
Return: Complete match by default else one or more matched subgroups depending on the arguments.
IndexError: If the group number passed as argument is negative or greater than the number of groups defined in the match pattern then an IndexError exception will be raised
AttributeError: If a matching pattern is not found then it raise AttributeError.
Consider the below example:
A program to print the username, company_name and domain from a emailID
firstname.lastname@example.org username geekforgeeks org ('username', 'geekforgeeks', 'org')
It’s time to understand the above program. We use a re.match() method to find a match in the given string(‘email@example.com‘) the ‘w‘ indicates that we are searching for an alphabetical character and the ‘+‘ indicates that we are searching for continuous alphabetical characters in the given string. Note the use of ‘()‘ the parenthesis is used to define different subgroups, in the above example, we have three subgroups in the match pattern. The result we get is a re.MatchObject which is stored in match_object.
Note: To know more about regex patterns refer Python regex
Depending on the arguments passed the group method returns us different strings and also it returns a tuple of matched strings.
If we pass an invalid group number in the method argument then we will get an IndexError exception.
Traceback (most recent call last): File "/home/8da42759204c98da7baa88422a4a74e0.py", line 17, in print(match_object.group(7)) IndexError: no such group
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course