Interview Prep/Python for DevOps/OS, filesystem, subprocess & CLIs

How do you use regular expressions for log parsing efficiently?

IntermediateConceptOS, filesystem, subprocess & CLIs
Answer

Compile once, use named groups, and anchor patterns.

import re
LINE = re.compile(r'^(?P<ip>\S+) \S+ \S+ \[(?P<ts>[^\]]+)\] "(?P<method>\S+) (?P<path>\S+) [^"]*" (?P<status>\d{3}) (?P<bytes>\d+|-)')
for line in f:
    if (m := LINE.match(line)):
        status = int(m["status"])

Use raw strings (r"...") so backslashes are not interpreted twice. re.match anchors at the start, re.search scans, re.fullmatch must match all. For simple splits, str.split() is much faster than a regex.

All Python for DevOps questions Roadmap: Python for automation

More on OS, filesystem, subprocess & CLIs