Python · guide
Python regex for log parsing: a practical guide
Logs are semi-structured text. Regular expressions turn each line into fields you can count and group.
Named groups
import re
line = "2026-11-18 10:42:07 ERROR payment failed user=482 amount=19.99"
pattern = re.compile(
r"(?P<ts>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) "
r"(?P<level>[A-Z]+) (?P<msg>.*)"
)
m = pattern.match(line)
if m:
print(m.group("level"), m.group("msg"))
Find all key=value pairs
pairs = dict(re.findall(r"(\w+)=(\S+)", line))
# {'user': '482', 'amount': '19.99'}
Tips
- Compile patterns you reuse in a loop.
- Use raw strings (r"...") so backslashes are not escaped twice.
- Always handle the no-match case: match() returns None.
- For large files, combine this with a generator that reads one line at a time.