search、match、fullmatch
三個函式都回傳 re.Match 或 None。差在掃描範圍。
| 函式 | 行為 |
|---|---|
re.search(pattern, string) |
在字串任意位置找第一處 |
re.match(pattern, string) |
只從開頭試;後面還有多餘字也可以 |
re.fullmatch(pattern, string) |
整串都必須符合 |
import re
text = "order-2026-A"
print(re.search(r"\d{4}", text)) # 找到 2026
print(re.match(r"\d{4}", text)) # None,開頭是 o
print(re.match(r"order", text)) # 匹配 order,後面還可以有字
print(re.fullmatch(r"order", text)) # None
print(re.fullmatch(r"order-\d{4}-A", text)) # 整串中
驗證使用者輸入時,優先 fullmatch,或自己在模式加 ^ 與 $。match 容易讓人以為「整串都對了」,其實只保證開頭對。
Match 物件
import re
m = re.search(r"(?P<code>[A-Z]+)-(?P<year>\d{4})", "ticket B-2026 done")
if m:
print(m.group(0), m.start(), m.end())
print(m.group("code"), m.group("year"))
print(m.span("year"))
group(0)/group():整段匹配start()/end()/span():在原字串的索引(切片用text[m.start():m.end()])groupdict():具名群組的字典
沒中就會是 None:
函式與編譯後的方法
re.search(pattern, string) 與 pattern.search(string) 等價,後者來自 re.compile,見 compile 與旗標。
import re
year = re.compile(r"\d{4}")
print(year.search("built in 2026"))
print(year.fullmatch("2026"))
print(year.fullmatch("2026-09")) # None
相關資料
- 下一頁:findall 與 finditer
- 語法:錨點
- 官方:
re.search