Regular expressions
Be able to match and extract patterns from text with regexes.
Prerequisites
- CPython — strings and text processingrequired
Intuition
| Pattern | Means | Matches |
|---|---|---|
\d | a digit | 7 |
\w | a letter, digit or _ | a, 3, _ |
\s | whitespace | a space, a tab |
. | any character at all | x |
+ | one or more | \d+ → 2026 |
* | zero or more | |
? | zero or one | |
{2,4} | between 2 and 4 | |
[abc] | one of a, b, c | |
^ $ | the start / the end of the line | |
(...) | a group that can be pulled out |
\d{4}-\d{2}-\d{2} matches a date like 2026-09-20.
Code
import re
log = "2026-09-20 13:05 ERROR user=42 message=timeout after 30s"
m = re.search(r"(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}) (\w+) user=(\d+)", log)
print(m.group(1), m.group(3), m.group(4)) # 2026-09-20 ERROR 42
# named groups are more readable
m = re.search(r"(?P<date>\d{4}-\d{2}-\d{2}).*user=(?P<uid>\d+)", log)
print(m.group("uid")) # 42
print(re.findall(r"\d+", log)) # ['2026','09','20','13','05','42','30']
print(re.sub(r"user=\d+", "user=***", log)) # mask the id
# raw strings: always use r"..." so that \d is not interpreted by Python
When a regex is the wrong tool: HTML and JSON (use a parser — nested structures cannot be matched with a regex), and patterns that grow longer than one line. A regex you cannot read in a month's time is a bug waiting to happen.
Mastery means
- Writes patterns with character classes, quantifiers and groups
- Extracts parts of a text with groups
- Knows when a regex is the wrong tool
Sign in to do the exercises and build your mastery up.