Python 正規表示式模式(re 模組)備忘單
Python 正規表示式參考指南。學習匹配、搜尋、findall、子和基本正規表示式模式。
核心模組方法
re 函式庫中用於文字查詢的標準函式介面。
| 方法/功能 | 文法 | 描述 |
|---|---|---|
| search() | re.search(pattern, string) | 掃描輸入字串以找到正規表示式模式匹配的第一個位置。 |
| match() | re.match(pattern, string) | 確定正規表示式模式是否從字串開頭開始匹配。 |
| findall() | re.findall(pattern, string) | 查找模式的所有非重疊符合項,傳回符合項清單。 |
| finditer() | re.finditer(pattern, string) | 傳回一個迭代器,產生所有符合項目的 MatchObject 實例。 |
| sub() | re.sub(pattern, repl, string) | 將字串中所有出現的模式替換為 repl。 |
| compile() | re.compile(pattern) | 將正規表示式模式編譯為正規表示式物件以供重複使用。 |
正規表示式元字元和簡寫
用於建立搜尋模式的構建塊。
| 方法/功能 | 文法 | 描述 |
|---|---|---|
| . | Match any character | 匹配除換行符之外的任何單一字元。 |
| ^ / $ | Anchor start / end | 符合字串的開頭 (^) 和字串的結尾 ($)。 |
| * / + / ? | Quantifiers | 代表 0 次或多次 (*)、1 次或多次 (+)、或 0 次或 1 次 (?) 重複。 |
| \d | Digit character | 相當於[0-9]類。 |
| \w | Alphanumeric character | 匹配字母數字字元和底線。 |
| \s | Whitespace character | 符合空格、製表符和換行符。 |
互動式簡報腳本
run_all_cheat_methods.py
在編輯器中執行# search()
re.search(pattern, string)
# match()
re.match(pattern, string)
# findall()
re.findall(pattern, string)
# finditer()
re.finditer(pattern, string)
# sub()
re.sub(pattern, repl, string)
# compile()
re.compile(pattern)
# .
Match any character
# ^ / $
Anchor start / end
# * / + / ?
Quantifiers
# \d
Digit character
# \w
Alphanumeric character
# \s
Whitespace character常見問題解答
re.match() 和 re.search() 有什麼不同?
re.match() 僅在字串的開頭檢查匹配,而 re.search() 則掃描整個字串以查找匹配。
如何在正規表示式匹配中捕獲組輸出?
在模式中使用括號 () 來定義群組,並使用 match_obj.group(1)、match_obj.group(2) 等檢索它們。
相關主題
推薦的 Python 資源
透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。