核心區別
| 方法 | 匹配範圍 | 行為 | 相當於 |
re.match(pattern, string) | 僅字符串開頭 | 從索引 0 開始匹配 | Perl m/^pattern/ |
re.search(pattern, string) | 字符串任意位置 | 掃描整串直到首次匹配 | Perl m/pattern/ (默認) |
代碼演示
import re
text = "helloworld, i am 30 !"
# search: 找到 "world" 於位置 5
m1 = re.search("world", text)
print(m1.group()) # world
# match: 開頭不是 "world",失敗
m2 = re.match("world", text)
print(m2) # None
# match: 開頭匹配 "helloworld"
m3 = re.match("helloworld", text)
print(m3.group()) # helloworld
何時用哪個?
- 驗證開頭格式(如協議頭、前綴):用
match — re.match(r'https?://', url)
- 提取任意位置內容(如解析日誌、查找關鍵字):用
search
- 需匹配整串:
match + 結尾 $,或 fullmatch (Py3.4+)
進階:預編譯與 Flags
# 預編譯提升性能
PATTERN = re.compile(r'\d{4}-\d{2}-\d{2}')
# 多行模式:^/$ 匹配每行開頭結尾
re.search(r'^ERROR', log, re.MULTILINE)
# 忽略大小寫
re.match(r'hello', text, re.IGNORECASE)
MatchObject 常用屬性/方法
m = re.search(r'(\w+)@(\w+\.\w+)', 'mail: test@example.com')
m.group() # 'test@example.com' (整個匹配)
m.group(1) # 'test' (第1組)
m.group(2) # 'example.com'
m.groups() # ('test', 'example.com')
m.start() # 6
m.end() # 22
m.span() # (6, 22)