re.MatchObject.groups() function in Python – Regex
Last Updated :
29 Aug, 2020
This method returns a tuple of all matched subgroups.
Syntax: re.MatchObject.groups()
Return: A tuple of all matched subgroups
AttributeError: If a matching pattern is not found then it raise AttributeError.
Consider the below example:
Example 1:
Python3
import re
match_object = re.match(r '(\d+)\-(\w+)\-(\w+)' ,
'498-ImperialCollege-London' )
detail_tuple = match_object.groups()
print (detail_tuple)
|
Output:
('498', 'ImperialCollege', 'London')
It’s time to understand the above program. We use a re.match() method to find a match in the given string(‘498-ImperialCollege-London‘) the ‘w‘ indicates that we are searching for a alphabetical character and the ‘+‘ indicates that we are searching for continuous alphabetical characters in the given string. Similarly d+ will match a consecutive set of numerical characters.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 variable.
Example 2: If a match object is not found then it raises AttributeError.
Python3
import re
match_object = re.match(r '(\d+)\-(\w+)\-(\w+)' ,
'1273984579846' )
print (match_object.groups())
|
Output:
Traceback (most recent call last):
File "/home/6510bd3e713a7b9a5629b30325c8a821.py", line 18, in
print(match_object.groups())
AttributeError: 'NoneType' object has no attribute 'groups'
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...