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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。