此方法返回所有匹配子组的元组。
用法: re.MatchObject.groups()
返回:所有匹配子组的元组
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'(\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)
输出:
('498', 'ImperialCollege', 'London')
现在是时候了解上述程序了。我们使用re.match()方法在给定的字符串('498-ImperialCollege-London')中找到匹配项,其中'w'表示我们正在搜索字母字符,而'+'表示我们正在搜索连续的字母字符。给定的字符串。类似地,d +将匹配一组连续的数字字符。请注意,括号中使用'()'来定义不同的子组,在上面的示例中,匹配模式中有三个子组,得到的结果是re.MatchObject存储在match_object变量中。
范例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'(\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())
输出:
Traceback (most recent call last): File "/home/6510bd3e713a7b9a5629b30325c8a821.py", line 18, in print(match_object.groups()) AttributeError:'NoneType' object has no attribute 'groups'
相关用法
注:本文由纯净天空筛选整理自haridarshanc大神的英文原创作品 re.MatchObject.groups() function in Python – Regex。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。