當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python Regex re.MatchObject.groups()用法及代碼示例


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

用法: 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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。