此方法返回一个字典,其中组名作为键,而匹配的字符串作为该键的值。
用法: re.MatchObject.groupdict()
返回:以组名作为键,并以匹配的字符串作为键的值的字典。
AttributeError:如果找不到匹配的模式,则会引发AttributeError。
考虑以下示例:
范例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'(?P<Username>\w+)@(?P<Website>\w+)\.(?P<Domain>\w+)', 'jon@geekforgeeks.org')
""" 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
The ?P<Username> in '()'(the round brackets) is
used to capture subgroups of strings satisfying
the above condition and the groupname is
specified in the ''(angle brackets)in this
case its Username."""
# generating a dictionary from the given emailID
details = match_object.groupdict()
# printing the dictionary
print(details)
输出:
{‘Username’:‘jon’, ‘Website’:‘geekforgeeks’, ‘Domain’:‘org’}
现在是时候了解上述程序了。我们使用re.match()方法在给定的字符串('jon@geekforgeeks.org')中找到匹配项。'w'表示我们正在搜索字母字符,而'+'表示我们正在搜索连续字母字符给定字符串中的字符。请注意,使用括号()来定义不同的子组,在上面的示例中,匹配模式中有三个子组。 “?P”语法用于定义用于捕获特定组的组名。我们得到的结果是一个re.MatchObject,它存储在match_object中。
要了解有关正则表达式模式的更多信息,请访问此文章。 Python正则表达式
范例2:如果未找到匹配对象,则引发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'(?P<Username>\w+)@(?P<Website>\w+)\.(?P<Domain>\w+)', '1234567890')
""" 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
The ?P<Username> in '()'(the round brackets) is
used to capture subgroups of strings satisfying
the above condition and the groupname is
specified in the ''(angle brackets)in this
case its Username."""
# Following line will raise AttributeError exception
print(match_object.groupdict())
输出:
Traceback (most recent call last): File "/home/fae2ec2e63d04a63d590c2e93802a002.py", line 21, in print(match_object.groupdict()) AttributeError:'NoneType' object has no attribute 'groupdict'
相关用法
注:本文由纯净天空筛选整理自haridarshanc大神的英文原创作品 re.MatchObject.groupdict() function in Python – Regex。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。