re.MatchObject.groups() function in Python – Regex

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
  
"""We create a re.MatchObject and store it in 
   match_object variable
   the '()' parenthesis are used to define a 
   specific group"""
  
match_object = re.match(r'(\d+)\-(\w+)\-(\w+)',
                        '498-ImperialCollege-London')
  
""" d in above pattern stands for numerical character
    w in above pattern stands for alphabetical character
    + is used to match a consecutive set of characters 
    satisfying a given condition so w+ will match a
    consecutive set of alphabetical characters
    d+ will match a consecutive set of numerical characters
    """
  
# generating the tuple with all matched groups
detail_tuple = match_object.groups()
  
# printing the tuple
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
  
"""We create a re.MatchObject and store it in 
   match_object variable
   the '()' parenthesis are used to define a 
   specific group"""
  
match_object = re.match(r'(\d+)\-(\w+)\-(\w+)'
                        '1273984579846')
  
""" w in above pattern stands for alphabetical character
    + is used to match a consecutive set of characters 
    satisfying a given condition so 'w+' will match a
    consecutive set of alphabetical characters
    """
  
# Following line will raise AttributeError exception
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'