Syllabus Lesson 47 of 244 · Files, Errors & Modules
Files, Errors & Modules

Pattern matching with regex

A regular expression (regex) is a tiny language for describing text patterns: "a level word, then a timestamp, then a message", or "anything that looks like an email". Python's re module runs them. You reach for regex when the structure is regular but the exact text varies.

Write patterns as raw strings (r"...") so backslashes mean what regex expects:

import re
m = re.search(r"\d+", "order 42 shipped")
print(m.group())   # 42

The pieces you will use most:

  • \d a digit, \w a word character (letter/digit/underscore), \s whitespace.
  • + one or more, * zero or more, ? optional. . is any character.
  • [abc] a character class (any one of a, b, c). ^ and $ anchor to the start and end.
  • Parentheses ( ) make a group you can pull out; (?P<name>...) names it.

re.search finds the first match (or None); m.group(1) or m.groupdict() reads the captured groups. re.findall returns every match:

text = "2026-07-09T12:00:00 [ERROR] disk full"
m = re.search(r"^(?P<ts>\S+) \[(?P<level>\w+)\] (?P<msg>.+)$", text)
print(m.group("level"))   # ERROR

print(re.findall(r"\d+", "3 cats, 12 dogs"))   # ['3', '12']
Your turn

Use the re module for both. (1) parse_log_line(line) matches a log line of the exact form TIMESTAMP [LEVEL] MESSAGE (for example 2026-07-09T12:00:00 [ERROR] disk full) and returns a dict {"timestamp": ..., "level": ..., "message": ...}, or None if the line does not match. The timestamp has no spaces, the level is one word in square brackets, and the message is the rest of the line. (2) find_emails(text) returns a list of every email address in text, in order. Treat an email as chars@chars.chars where the local part and domain use letters, digits and the symbols . _ + -.

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output