On this page
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
- Always use raw strings (
r"..."): Withoutr,\bis a backspace character and\dtriggers aSyntaxWarning. re.match()only anchors at the start of the string: Usere.search()to match anywhere, orre.fullmatch()to require the entire string to match.- Beware catastrophic backtracking (ReDoS): Avoid nested quantifiers like
(a+)+on untrusted input; bound input length before running regexes. - Quantifiers are greedy by default: Use
*?/+?for non-greedy matches, or negated character classes like[^"]+for cleaner, faster matching.
Common Functions
- re.compile() —
compile(pattern, flags=0)— Compile a regular expression pattern, returning a Pattern object. - re.escape() —
escape(pattern)— Escape special characters in a string. - re.findall() —
findall(pattern, string, flags=0)— Return a list of all non-overlapping matches in the string. - re.finditer() —
finditer(pattern, string, flags=0)— Return an iterator over all non-overlapping matches in the string. For each match, the iterator returns a Match object. - re.fullmatch() —
fullmatch(pattern, string, flags=0)— Try to apply the pattern to all of the string, returning a Match object, or None if no match was found. - re.match() —
match(pattern, string, flags=0)— Try to apply the pattern at the start of the string, returning a Match object, or None if no match was found. - re.purge() —
purge()— Clear the regular expression caches - re.search() —
search(pattern, string, flags=0)— Scan through string looking for a match to the pattern, returning a Match object, or None if no match was found. - re.split() —
split(pattern, string, maxsplit=0, flags=0)— Split the source string by the occurrences of the pattern, returning a list containing the resulting substrings. If capturing parentheses are used in pattern, then the text of all - re.sub() —
sub(pattern, repl, string, count=0, flags=0)— Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; - re.subn() —
subn(pattern, repl, string, count=0, flags=0)— Return a 2-tuple containing (new_string, number).
Classes & Objects
- re.error — Exception raised for invalid regular expressions. (Methods:
.add_note(),.with_traceback()) - re.Match — The result of re.match() and re.search(). (Methods:
.end(),.expand(),.group(),.groupdict(),.groups(),.span()) - re.Pattern — Compiled regular expression object. (Methods:
.findall(),.finditer(),.fullmatch(),.match(),.scanner(),.search()) - re.PatternError — Exception raised for invalid regular expressions. (Methods:
.add_note(),.with_traceback()) - re.RegexFlag — An enumeration. (Methods:
.as_integer_ratio(),.bit_count(),.bit_length(),.conjugate(),.from_bytes(),.is_integer())
Constants & Attributes
re.A(RegexFlag) =re.ASCIIre.ASCII(RegexFlag) =re.ASCIIre.DOTALL(RegexFlag) =re.DOTALLre.I(RegexFlag) =re.IGNORECASEre.IGNORECASE(RegexFlag) =re.IGNORECASEre.L(RegexFlag) =re.LOCALEre.LOCALE(RegexFlag) =re.LOCALEre.M(RegexFlag) =re.MULTILINEre.MULTILINE(RegexFlag) =re.MULTILINEre.NOFLAG(RegexFlag) =re.NOFLAGre.S(RegexFlag) =re.DOTALLre.U(RegexFlag) =re.UNICODEre.UNICODE(RegexFlag) =re.UNICODEre.VERBOSE(RegexFlag) =re.VERBOSEre.X(RegexFlag) =re.VERBOSE
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/difflib
- tuts/python3/stdlib_module/random
- tuts/python3/stdlib_module/re/compile
- tuts/python3/stdlib_module/re/error
- tuts/python3/stdlib_module/re/escape
- tuts/python3/stdlib_module/re/findall
- tuts/python3/stdlib_module/re/finditer
- tuts/python3/stdlib_module/re/fullmatch
- tuts/python3/stdlib_module/re/match
- tuts/python3/stdlib_module/re/Match_class
- tuts/python3/stdlib_module/re/Pattern
- tuts/python3/stdlib_module/re/PatternError
- tuts/python3/stdlib_module/re/purge
- tuts/python3/stdlib_module/re/RegexFlag
- tuts/python3/stdlib_module/re/search
- tuts/python3/stdlib_module/re/split
- tuts/python3/stdlib_module/re/sub
- tuts/python3/stdlib_module/re/subn
- tuts/python3/stdlib_module/readline
- tuts/python3/stdlib_module/rlcompleter
- tuts/python3/stdlib_module/sre_compile
- tuts/python3/stdlib_module/sre_constants
- tuts/python3/stdlib_module/sre_parse
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/string
- tuts/python3/stdlib_module/stringprep
- tuts/python3/stdlib_module/textwrap
- tuts/python3/stdlib_module/unicodedata
Related notes
- tuts/python3/stdlib_module/difflib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/random Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/re/compile Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/re/error Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/re/escape Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/re/findall Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/re/finditer Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/re/fullmatch Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/re/match Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/re/Match_class Linked here; links to this page; shared tags: #stdlib