此方法返回一個字典,其中組名作為鍵,而匹配的字符串作為該鍵的值。
用法: 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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。