On this page
  1. re
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Precompiled Patterns with finditer() & Named Groups
  7. 2. Function-Driven Substitution with re.sub()
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

re

Prev: random | Up: stdlib_module | Next: readline
Rel: string, difflib, textwrap, unicodedata, stringprep
Ref: docs.python.org — re
Tags: #public #python3 #stdlib


Import

import re

Overview

Regular expression matching, extraction, and substitution for strings and bytes. Reach for re when simple string methods (in, startswith, split, partition) aren't expressive enough; precompile patterns with re.compile() when reused in loops, and avoid regex for nested HTML/XML/JSON (use json or a real parser).

Quick Start

import re

match = re.search(r"(?P<user>[a-z]+)@(?P<host>[a-z.]+)", "Contact: ada@example.org")
assert match is not None
assert match.group("user") == "ada"
assert match.groupdict() == {"user": "ada", "host": "example.org"}

Implementation Walkthrough

1. Precompiled Patterns with finditer() & Named Groups

finditer() yields Match objects lazily (giving access to .span(), .group(), and .groupdict()) without allocating a full list of strings:

import re

LOG_LINE = re.compile(r"^(?P<level>INFO|WARN|ERROR):\s+(?P<msg>.+)$", re.MULTILINE)
sample = "INFO: started\nERROR: disk full\nWARN: retrying"

errors = [m.group("msg") for m in LOG_LINE.finditer(sample) if m.group("level") == "ERROR"]
assert errors == ["disk full"]

2. Function-Driven Substitution with re.sub()

Pass a callable to re.sub() for dynamic replacements without messy backreferences:

import re

def redact_digits(match: re.Match[str]) -> str:
    return "*" * len(match.group(0))

assert re.sub(r"\d{4}", redact_digits, "Card 4242-1111") == "Card ****-****"

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes