re - Regular Expressions
The re module matches, searches, and substitutes text via regex. Compile patterns for reuse; use raw strings r"..." for readable escapes; prefer str methods when regex is overkill.
Search across all documentation pages
The re module matches, searches, and substitutes text via regex. Compile patterns for reuse; use raw strings r"..." for readable escapes; prefer str methods when regex is overkill.
import re
EMAIL = re.compile(r"^[\w.+-]+@[\w-]+\.[\w.-]+$")
def valid_email(value: str) -> bool:
return bool(EMAIL.match(value))When to reach for this:
import re
LOG_LINE = re.compile(
r"^(?P<level>INFO|ERROR)\s+(?P<msg>.+)$"
)
def parse_log_lines(text: str) -> list[dict[str, str]]:
rows = []
for line in text.strip().splitlines():
m = LOG_LINE.match(line)
if m:
rows.append(m.groupdict())
return rows
sample = "INFO started\nERROR disk full\n"
print(parse_log_lines(sample))
redacted = re.sub(r"\b\d{4}-\d{4}-\d{4}-\d{4}\b", "[CARD]", "4111-1111-1111-1111")
print(redacted)What this demonstrates:
(?P<name>...)match anchors start; search scans anywheresub replaces sensitive data patterns| Method | Purpose |
|---|---|
re.search | First match anywhere |
re.match | Start of string |
re.findall | All non-overlapping |
re.sub | Replace |
re.IGNORECASE, re.MULTILINE, re.DOTALLre.compile(..., flags) combinematch misses mid-string. Fix: pick correct method.\w - unicode surprises. Fix: explicit character classes [A-Za-z0-9_].| Alternative | Use When | Don't Use When |
|---|---|---|
| str.split/partition | Fixed delimiter | Variable pattern |
| parsimonious/lark | Grammar languages | Simple extract |
| pandas str.extract | Columnar data | Single string |
Not required but r"\n" vs "\\n" clarity strongly recommended.
Returns tuples if multiple capturing groups - use finditer for objects.
*?, +? lazy quantifiers - match minimal span.
re.compile(r"...", re.VERBOSE) allows comments and whitespace in pattern.
Default unicode str patterns in Python 3; use (?a) for ASCII-only when needed.
sub(pattern, repl, s, count=1) limit replacements.
(?=...) positive lookahead - assert without consuming.
Table-driven cases in pytest; document pattern in docstring.
Do not parse JSON with regex - use json module.
regex module adds features; stdlib sufficient for most services.
Stack versions: This page was written for Python 3.14.0 (stable 3.14, maintenance 3.13), FastAPI 0.115+, Django 5.2, Flask 3.1, Pydantic 2, PyTorch 2.6+, pandas 2.2+, Polars 1.x, ruff 0.9+, and uv 0.6+.
Reviewed by Chris St. John·Last updated Jul 19, 2026