match / search / fullmatch

40.4 match / search / fullmatch

re.match(模式, 文本) — 从字符串开头匹配,开头不对返回 None。

re.search(模式, 文本) — 全文找第一个匹配,最常用。

re.fullmatch(模式, 文本) — 整串必须完全匹配。

匹配成功返回 Match 对象,用 .group() 取内容;失败为 None。

三种匹配对比

# ========================================
# 示例:match / search / fullmatch
# 说明:search 最灵活;fullmatch 做完整校验
# ========================================
import re

text = '我的手机13812345678结束'

m1 = re.match(r'1\d{10}', text)   # None,开头不是1
m2 = re.search(r'1\d{10}', text)  # 找到手机号
m3 = re.fullmatch(r'1\d{10}', '13812345678')  # 整串是手机号才成功

print('search:', m2.group() if m2 else None)
print('fullmatch:', m3.group() if m3 else None)