Python Regular Expressions for Logs
Log lines are the one place automation genuinely needs regular expressions: the shape is fixed enough to match and irregular enough that split() will not do it. This guide covers the parts that matter - search against match, named groups, compiling once, greedy against lazy quantifiers, sub for redaction - against a real access log with one deliberately malformed line in it.
Files and Data Formats Guide 14 of 39 Intermediate
- Control nodeUbuntu 26.04 LTS
- Python3.14.4
- requests2.34.2
- paramiko5.0.0
- TimeAbout 20 min
The re module is stable across Python 3. Since 3.12 an unrecognised escape in a non-raw string is a SyntaxWarning, which this guide runs into and which is the argument for always writing patterns as raw strings.
- pytest9.1.1
- PyYAML6.0.3
- boto3 / botocore1.43.78
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| RUNNER01 | 192.168.0.27 | Ubuntu 26.04 LTS | Control node - every script in this path runs here | 2 Core | 4 GB | 50 GB |
This guide includes
Use this for log lines, which is where automation genuinely needs a regular expression. This matters because search, match and fullmatch ask three different questions - and some of this work should not use a regex at all.
- separating
search,matchandfullmatch - reading what a match object carries, and naming groups so a script can use them
- compiling once and using it in a loop, with
findallandfinditer - meeting greedy against lazy, and the escaping that bites
- rewriting with
sub, and knowing when to use string methods instead
Before you start
-
The log this guide works on
-
search, match and fullmatch are three questions
-
What a match object carries
-
Named groups, which is what a script should use
-
Compile once, use in a loop
-
findall and finditer
-
Greedy against lazy
-
The escaping that bites
-
sub, for rewriting rather than reading
-
split, and the flags worth knowing
-
And when not to use a regex