Guides / Python

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

Practise it

Share on LinkedIn

Practise this for free

Run real code, get instant checks and keep your progress. Free to join with Google.

Start free → Choose a career path

More guides