正規表現の高度なパターン
名前付きグループ、先読み、およびあいまい一致。
概要
regex パッケージは、Python 組み込み re のドロップイン置換として機能します。
これは、あいまい検索ツリーと独立した名前付きグループ化辞書をすぐに使用できるように広範囲にサポートします。
コードと実行の出力
セキュリティ ログ レイアウトを解析し、1 つの置換あいまい一致を実行します。
fuzzy.py
エディターで試してみる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+)\s+\[(?P<module>\w+)\] (?P<message>.+)"
m = regex.match(pattern, log)
if m:
print("Match Breakdown:")
for k, v in m.groupdict().items():
print(f" {k:<10}: {v}")
# Fuzzy matching (allows 1 substitution)
print("\nFuzzy search for 'colour' (≤1 error):")
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()}")端子出力
Match Breakdown:
date : 2025-07-04
time : 14:32:01
level : ERROR
module : auth
message : Login failed for user@example.com
Fuzzy search for 'colour' (≤1 error):
found 'colour' at (9, 15)
found 'colouur' at (30, 37)段階的な実装
- 正規表現によるテキストデータの解析
- ファジーログスクレイピング
- 文字列正規化パターン