Python re Module
Practical regular expressions with compiled patterns and groups.
- python re
- re.compile
- findall
- named groups
- regex sub
Python re Module
Practical regular expressions with compiled patterns and groups.
Commands
| Command | What it does |
|---|---|
re.compile(r"\d{4}-\d{2}-\d{2}") | Compile once, reuse |
pattern.search(text) | First match anywhere |
pattern.findall(text) | All matches |
pattern.sub("X", text) | Replace matches |
re.split(r"\s*,\s*", s) | Split on comma + spaces |
Example
import re
pat = re.compile(r"(?P<year>\d{4})-(?P<month>\d{2})")
m = pat.search("release 2026-10")
print(m.groupdict()) # {'year': '2026', 'month': '10'}
FAQ
search vs match?
search scans the whole string; match anchors at the start — most bugs come from using match unintentionally.
Why raw strings?
Backslashes stay literal (r"\d" not "\\d"); always write patterns as r"...".
SSS
search vs match?
search scans the whole string; match anchors at the start — most bugs come from using match unintentionally.
Why raw strings?
Backslashes stay literal (r"\d" not "\\d"); always write patterns as r"...".
Python
Python Venv and Environments
Isolate dependencies per project with venv and pinned requirements.
Python Pip Essentials
Install, upgrade, and audit packages with pip like a pro.
Python Basics
Syntax survival kit: variables, loops, f-strings, and errors.
Python Strings
Slice, split, join, and format text efficiently.