Python re 模块
compile, match vs search vs fullmatch, flags, and substitution callbacks.
Key Points`re.match` only anchors at position 0 — for validation use `re.fullmatch`, for search anywhere use `re.search`.
Three Entry Points
| Function | Anchored | Use for |
|---|---|---|
| match | Start only | Prefix check |
| search | Anywhere, first hit | Existence / extract |
| fullmatch | Whole string | Validation |
Python
import re
print(bool(re.match(r"\d+", "abc123"))) # False
print(bool(re.search(r"\d+", "abc123"))) # True
print(bool(re.fullmatch(r"\d+", "123"))) # True
print(bool(re.fullmatch(r"\d+", "123abc"))) # FalseOutput
False
True
True
FalseCompile and Flags
re.compile parses the pattern once — worth it in loops. Combine flags with |.
Python
import re
PHONE = re.compile(r"^1[3-9]\d{9}$")
print(bool(PHONE.fullmatch("13800138000")))
word = re.compile(r"error", re.I) # 忽略大小写
print(word.findall("ERROR Error error"))
print(re.findall(r"^b", "a\nb\nc", re.M)) # 多行模式Output
True
['ERROR', 'Error', 'error']
['b']Substitution with a Callback
The replacement in re.sub can be a function receiving the match — ideal for masking or templating.
Python
import re
def mask(m):
s = m.group(0)
return s[:3] + "*" * (len(s) - 7) + s[-4:]
print(re.sub(r"\d{11}", mask, "联系 13800138000 或 13912345678"))Output
联系 138****8000 或 139****5678Never parse HTML or JSON with regex — nested structures break it. Use BeautifulSoup and
json.loads.三个入口
| 函数 | 锚定 | 适用 |
|---|---|---|
| match | 仅开头 | 前缀判断 |
| search | 任意位置首个 | 判断存在、提取 |
| fullmatch | 整串 | 格式校验 |
Python
import re
print(bool(re.match(r"\d+", "abc123"))) # False
print(bool(re.search(r"\d+", "abc123"))) # True
print(bool(re.fullmatch(r"\d+", "123"))) # True
print(bool(re.fullmatch(r"\d+", "123abc"))) # FalseOutput
False
True
True
False预编译与标志
同一模式重复使用时 re.compile 只编译一次,循环里能省下可观的解析开销。标志位用 | 组合。
Python
import re
PHONE = re.compile(r"^1[3-9]\d{9}$")
print(bool(PHONE.fullmatch("13800138000")))
word = re.compile(r"error", re.I) # 忽略大小写
print(word.findall("ERROR Error error"))
print(re.findall(r"^b", "a\nb\nc", re.M)) # 多行模式Output
True
['ERROR', 'Error', 'error']
['b']带回调的替换
re.sub 的第二个参数可以是函数,收到 match 对象、返回替换文本 —— 适合做脱敏、模板填充这类「按内容决定替换结果」的场景。
Python
import re
def mask(m):
s = m.group(0)
return s[:3] + "*" * (len(s) - 7) + s[-4:]
print(re.sub(r"\d{11}", mask, "联系 13800138000 或 13912345678"))Output
联系 138****8000 或 139****5678不要用正则解析 HTML 或 JSON —— 嵌套结构用正则必然出错。HTML 用 BeautifulSoup,JSON 用
json.loads。