C

Python › Module 4 › Lesson 1

BeginnerModule 4Lesson 1/4

Regex for Security Logs

Use regular expressions to extract IPs, status codes, and failed-login patterns from logs

15 min+52 XP3 quiz
Module progress1 of 4
a3f9c2…
Regex · Extract fields

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

1

re.search is used to:

Multiple choice

Knowledge Check

2

True or False: Raw strings (r"...") help write regex with backslashes.

True or False

Knowledge Check

3

In security logs, regex often extracts:

Multiple choice

← Previous

Answer all 3 knowledge checks to continue. (0/3 answered)