Regular 表达式
Match and extract 文本模式使用 re 模块: 搜索, match, 分组, and substitution.
你将学到
- Use re.搜索, re.match, and re.findall
- Capture 分组使用 parentheses
- Apply quantifiers, anchors, and character 类
- Substitute 文本使用 re.sub
- 编译模式 for reuse and 性能
概念讲解
The re Module
Python's re module provides regular expression support. A regex is a pattern that describes a set of strings — useful for validation, extraction, and substitution:
import re
# Search for a pattern in a string
match = re.search(r"\d{3}", "Call 555-1234 for help")
if match:
print(match.group()) # 555
print(match.start()) # 5 (position where match starts)
Always use raw strings (r"...) for regex 模式 — 不使用 r` prefix, Python interprets backslash escapes before the regex engine sees them, causing subtle bugs.