regex
Parsing高階正規表示式引擎
概述 regex
regex 模組是 Python 內建 re 模組的直接替代品,提供附加功能,包括模糊匹配(近似字串匹配)、可變寬度後向查找、具有重複捕獲的命名捕獲組、POSIX 字符類和原子分組。
正規表示式可透過 micropip 在PyRun中使用。當您需要匹配具有輕微拼字錯誤的模式(模糊匹配)、處理複雜的 Unicode 文字或使用標準 re 模組不支援的正規表示式功能時,它特別有用。
程式碼和執行輸出
命名捕獲組和模糊模式匹配。
Regex: Named Groups & Fuzzy在編輯器中執行
import regex
# Named capture groups — parse a log line
log = "2025-07-04 14:32:01 ERROR [auth] Login failed for user@example.com"
pattern = r"(?P<date>\d{4}-\d{2}-\d{2}) (?P<time>\d{2}:\d{2}:\d{2}) (?P<level>\w+) \[(?P<module>\w+)\] (?P<message>.+)"
m = regex.match(pattern, log)
if m:
for k, v in m.groupdict().items():
print(f" {k:<10}: {v}")
# Fuzzy matching — find 'colour' with up to 1 error
print("\nFuzzy search (≤1 substitution):")
text = "I prefer colour and cilor and colouur"
for hit in regex.finditer(r"(?:colour){s<=1}", text):
print(f" found '{hit.group()}' at {hit.span()}")相關套餐
推薦的 Python 資源
透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。
Python教學
Python 正規表示式:使用 re 模組進行模式匹配
掌握 Python 中的正規表示式 (Regex)。學習使用內建 re 庫搜尋、匹配、拆分和替換字串資料。
查看資源
操作指南
如何在 Python 中對列表進行排序(升序和降序)
了解如何在 Python 中使用 sort() 方法和sorted() 函數對清單進行排序。發現自訂鍵排序和逆序範例。
查看資源
備忘錄
Python 正規表示式模式(re 模組)備忘單
Python 正規表示式參考指南。學習匹配、搜尋、findall、子和基本正規表示式模式。
查看資源
語言比較
Python 與 JavaScript:哪種程式語言最好?
Python 和 JavaScript 的全面比較。探索語法差異、效能、用例(後端與前端)和編碼範例。
查看資源