以匹配手机号为例
代码
import re
phone_number = "phone:15647854549"
# 分组
match_obj = re.match("(phone:)(1[0-9]{10}$)", phone_number)
if match_obj:
result = match_obj.group()
print(result) # phone:15647854549
result1 = match_obj.group(1)
print(result1) # phone:
result2 = match_obj.group(2)
print(result2) # 15647854549
else:
print("匹配失败")
解释
1.match_obj = re.match("(phone:)(1[0-9]{10}$)", phone_number)
上面的代码中(phone:)表示分组1,后面的小括号表示分组2
2.分组是默认是从1开始的,group(1)匹配的是(phone:)
3.group()括号中默认是0,表示将匹配到的结果全部(包括分组1和分组 2)打印出来