本頁重點提要

  • 01.compile 後重複使用 pattern 更乾淨也更快。
  • 02.groupdict() 直接得到結構化資料。
  • 03.複雜問題不要一條 regex 解全世界,拆步驟更好維護。

整合實戰:Log 解析成結構化 dict

最後我們把前面學到的「命名群組 + finditer」串起來。你會得到一份可以直接丟進資料庫或做報表的 dict。

import re

logs = [
  "2026-02-10 10:12:03 INFO user=jerry id=8511956003 action=login",
  "2026-02-10 10:13:10 WARN user=jerry id=8511956003 action=retry",
  "2026-02-10 10:14:55 ERROR user=jerry id=8511956003 action=failed",
]

pat = re.compile(
  r"(?P<date>\d{4}-\d{2}-\d{2})\s+(?P<time>\d{2}:\d{2}:\d{2})\s+(?P<level>INFO|WARN|ERROR)\s+user=(?P<user>\w+)\s+id=(?P<id>\d+)\s+action=(?P<action>\w+)"
)

rows = []
for line in logs:
  m = pat.search(line)
  if not m:
    continue
  rows.append(m.groupdict())

print(rows[0])

最後的實務建議

  • compile 就 compile:同一個 pattern 會被用很多次。
  • 先寫「最小可用」pattern,再逐步加群組與限制(不要一次寫超長)。
  • 遇到複雜狀況:先把資料切小段,再做多次 regex,而不是一條 regex 解全世界。

Implementation Reference
import re

pat = re.compile(r"(?P<level>INFO|WARN|ERROR)")
print(pat.search("2026-02-10 10:14:55 ERROR").group("level"))
Switch Page