re.MatchObject.groupdict() function in Python – Regex
This method returns a dictionary with the groupname as keys and the matched string as the value for that key.
Syntax: re.MatchObject.groupdict()
Return: A dictionary with groupnames as the keys and matched string as the value for the key.
AttributeError: If a matching pattern is not found then it raise AttributeError.
Consider the below example:
Example 1:
A program to create and print a detailed dictionary which will consist of username, website, and the domain.
Python3
import re
match_object = re.match(
r '(?P<Username>\w+)@(?P<Website>\w+)\.(?P<Domain>\w+)' , 'jon@geekforgeeks.org' )
details = match_object.groupdict()
print (details)
|
Output:
{‘Username’: ‘jon’, ‘Website’: ‘geekforgeeks’, ‘Domain’: ‘org’}
It’s time to understand the above program. We use a re.match() method to find a match in the given string(‘jon@geekforgeeks.org‘) 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 ‘?P‘ syntax is used to define the groupname for capturing the specific groups. The result we get is a re.MatchObject which is stored in match_object.
To know more about regex patterns visit this post. Python regex
Example 2: If a match object is not found then it raises AttributeError.
Python3
import re
match_object = re.match(
r '(?P<Username>\w+)@(?P<Website>\w+)\.(?P<Domain>\w+)' , '1234567890' )
print (match_object.groupdict())
|
Output:
Traceback (most recent call last):
File "/home/fae2ec2e63d04a63d590c2e93802a002.py", line 21, in
print(match_object.groupdict())
AttributeError: 'NoneType' object has no attribute 'groupdict'
Last Updated :
29 Aug, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...