📜  Python中的 re.MatchObject.groups()函数– 正则表达式

📅  最后修改于: 2022-05-13 01:55:06.574000             🧑  作者: Mango

Python中的 re.MatchObject.groups()函数– 正则表达式

此方法返回所有匹配子组的元组。

考虑下面的例子:

示例 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)


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())


输出:

('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'