Python re 模块

compile, match vs search vs fullmatch, flags, and substitution callbacks.

Intermediate
Key Points`re.match` only anchors at position 0 — for validation use `re.fullmatch`, for search anywhere use `re.search`.

Three Entry Points

FunctionAnchoredUse for
matchStart onlyPrefix check
searchAnywhere, first hitExistence / extract
fullmatchWhole stringValidation
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")))   # False
Output
False
True
True
False

Compile 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****5678
Never parse HTML or JSON with regex — nested structures break it. Use BeautifulSoup and json.loads.

Friends & Partners