Python Regex group() Method Guide

In Python, group() is one of the methods in regular expressions that is used to return the matching string from the regular expression pattern.

There are two ways to use the group() method.

  1. – team()
  2. index within a group

Here is an example using the group() method:

import re

pattern = r"(\d{3})-(\d{3}-\d{4})"
phone_number = "123-456-7890"

match = re.search(pattern, phone_number)
if match:
    # 返回整个匹配的字符串
    print(match.group())  # 输出:123-456-7890
    
    # 返回第一个分组(分组号为1)匹配的字符串
    print(match.group(1))  # 输出:123
    
    # 返回第二个分组(分组号为2)匹配的字符串
    print(match.group(2))  # 输出:456-7890

Please note that if no content is matched when using the group() method, an AttributeError exception will be thrown. Therefore, it is advisable to first use methods like re.search() to check for successful matches before using the group() method.

bannerAds