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.
More on OS, filesystem, subprocess & CLIs
`os.path` vs `pathlib`: which do you use and why?BeginnerHow do you read environment variables safely?BeginnerHow do you walk a directory tree and find files?BeginnerWhat does `shutil` give you that `os` does not?BeginnerHow do you run an external command correctly with `subprocess`?BeginnerWhy is `shell=True` dangerous, and when is it acceptable?Intermediate