Python › Module 4 › Lesson 1
Regex for Security Logs
Use regular expressions to extract IPs, status codes, and failed-login patterns from logs
Opening
When "in line" is not enough
Substring search finds “Failed password.” Regex extracts the IP that follows “from ” even when lines vary. You already used a taste of this in the log analyzer lab—now make it deliberate.
1. Python re Basics
Extract IPv4 addressesimport re line = "Failed password for root from 203.0.113.10 port 44022" pattern = r"(\\d{1,3}(?:\\.\\d{1,3}){3})" match = re.search(pattern, line) if match: print(match.group(1))
import re
line = "Failed password for root from 203.0.113.10 port 44022"
pattern = r"(\\d{1,3}(?:\\.\\d{1,3}){3})"
match = re.search(pattern, line)
if match:
print(match.group(1))2. Tips That Keep You Sane
Raw strings
Use r"..." so backslashes behave.
Start simple
Find the field, then tighten the pattern.
Test on samples
Keep 5–10 example lines as unit fixtures.
Readable > clever
A slightly longer regex you understand beats a one-line monster nobody can debug at 2 a.m.
Knowledge Check
re.search is used to:
Multiple choice
Knowledge Check
True or False: Raw strings (r"...") help write regex with backslashes.
True or False
Knowledge Check
In security logs, regex often extracts:
Multiple choice