以下是 Python 正则表达式中 match 和 fullmatch 的 4 个经典案例,每个案例都包含数据提取的实际应用。
案例 1:提取日期(年-月-日)------ 使用 match
场景 :从字符串开头匹配并提取 YYYY-MM-DD 格式的日期。
方法 :re.match(要求从起始位置匹配)。
python
import re
text = "2025-12-25 是圣诞节"
pattern = r"(\d{4})-(\d{2})-(\d{2})"
match = re.match(pattern, text)
if match:
year, month, day = match.groups()
print(f"年: {year}, 月: {month}, 日: {day}")
else:
print("未匹配")
输出:
年: 2025, 月: 12, 日: 25
案例 2:验证完整的邮箱地址 ------ 使用 fullmatch
场景 :检查整个字符串是否为一个合法的邮箱(基础验证)。
方法 :re.fullmatch(要求整个字符串完全匹配)。
python
import re
email = "user_123@example.com"
pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
match = re.fullmatch(pattern, email)
if match:
print(f"有效邮箱: {match.group()}")
# 提取用户名和域名(需要分组)
pattern2 = r"([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})"
parts = re.fullmatch(pattern2, email)
print(f"用户名: {parts.group(1)}, 域名: {parts.group(2)}")
else:
print("无效邮箱")
输出:
有效邮箱: user_123@example.com
用户名: user_123, 域名: example.com
案例 3:提取电话号码(美国格式)------ 使用 match
场景 :字符串开头为 (XXX) XXX-XXXX 或 XXX-XXX-XXXX 格式的电话号码。
方法 :re.match + 可选分组提取区号和号码。
python
import re
text = "(123) 456-7890 转分机"
pattern = r"\(?(\d{3})\)?[- ]?(\d{3})-(\d{4})"
match = re.match(pattern, text)
if match:
area, first, last = match.groups()
print(f"区号: {area}, 号码: {first}-{last}")
else:
print("未匹配")
输出:
区号: 123, 号码: 456-7890
案例 4:验证 IPv4 地址 ------ 使用 fullmatch
场景 :检查整个字符串是否为合法的 IPv4 地址(0-255 范围)。
方法 :re.fullmatch + 提取四个字节的数值。
python
import re
ip = "192.168.1.100"
# 每个字段:0-255(避免前导零过复杂,这里简化但覆盖范围)
pattern = r"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
match = re.fullmatch(pattern, ip)
if match:
a, b, c, d = map(int, match.groups())
print(f"IP 合法: {a}.{b}.{c}.{d}")
else:
print("非法 IP")
输出:
IP 合法: 192.168.1.100
总结:match vs fullmatch
| 方法 | 匹配要求 | 典型用途 |
|---|---|---|
match |
从字符串开头匹配,不要求匹配到结尾 | 提取开头的固定格式数据(如日期、ID) |
fullmatch |
要求整个字符串完全匹配 | 验证用户输入、检查字符串是否完全符合规则 |
以上案例展示了两种方法的典型应用,并演示了如何通过分组提取关键数据。