Hands-on Lab·Python Automation for IT
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
- Python3.14.4
- Control nodeUbuntu 26.04 LTS
- Managed hostsRHEL 10.0
- requests2.34.2
- paramiko5.0.0
- pytest9.1.1
- PyYAML6.0.3
- boto3 / botocore1.43.78
- TimeAbout 20 min
- Reviewed24 August 2026
Written against the versions above. 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.
| 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 |
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