The re module is Python's standard library interface for regular expressions. You use it to search text for patterns, check that a string has a certain format, extract parts of a string, replace matches and split text on complex separators. It covers tasks such as validating input, parsing log lines and cleaning data.
A regular expression is a small pattern language. Python compiles the pattern, then matches it against a string and returns a match object (or None) so you can read what matched.
Always write patterns as raw strings (r"...") so backslashes reach the regex engine unchanged.
| Function | What it does |
|---|---|
re.match(p, s) | Matches only at the beginning of s |
re.search(p, s) | Finds the first match anywhere in s |
re.fullmatch(p, s) | Succeeds only if the whole string matches |
re.findall(p, s) | Returns a list of all non-overlapping matches (or groups) |
re.finditer(p, s) | Returns an iterator of match objects, useful for positions |
re.sub(p, repl, s) | Replaces matches |
re.split(p, s) | Splits on matches |
re.compile(p) | Returns a reusable pattern object |
match, search and fullmatch return None when nothing matches, so check the result before calling .group().
Parentheses capture parts of a match. Named groups make code easier to read.
Use (?:...) for a group that groups but does not capture. When a pattern has groups, findall() returns the group contents instead of the whole match, which surprises many beginners.
re.sub() accepts either a replacement string or a function. In a replacement string, \1 or \g<name> refer to captured groups.
The optional count argument limits replacements, and re.subn() returns the new string together with the number of replacements made. If you only need to replace a fixed substring, str.replace() is simpler and faster.
| Syntax | Meaning |
|---|---|
. | Any character except a newline |
\d, \w, \s | Digit, word character, whitespace (\D, \W, \S are the opposites) |
^, $ | Start and end of string (or line with re.MULTILINE) |
\b | Word boundary |
*, +, ? | Zero or more, one or more, zero or one |
{n,m} | Between n and m repetitions |
*?, +? | Lazy versions that match as little as possible |
[abc], [^abc] | A character class and its negation |
| `a | b` |
(?=...), (?<=...) | Lookahead and lookbehind assertions |
Flags change how a pattern behaves. Combine them with |. The re.VERBOSE flag lets you add whitespace and comments to a complex pattern.
Other useful flags are re.MULTILINE (^ and $ match at each line), re.DOTALL (. also matches newlines) and re.ASCII (limit \w, \d and \s to ASCII). By default, patterns on str are Unicode-aware. The module caches recently compiled patterns, but compiling once with re.compile() makes the intent clear and avoids repeated lookups in hot loops.
html.parser, json or xml.etree.(a+)+$ can take exponential time on crafted input, which is a denial-of-service risk when patterns run on user data. Keep patterns simple, anchor them, and avoid ambiguous repetition.a++) and atomic groups ((?>...)), which prevent backtracking where you do not need it.re.match() when you want re.search(). match only tests the start of the string.re.VERBOSE for anything longer than a one-liner, so the next reader can maintain it.re.match() and re.search()?re.match() only succeeds if the pattern matches at the very start of the string. re.search() scans the whole string and returns the first match. For a whole-string test, use re.fullmatch().
findall() return tuples?When the pattern contains more than one capturing group, findall() returns a list of tuples with one entry per group. Use non-capturing groups (?:...) or finditer() if you want whole matches.
re.compile()?It is optional for performance, because Python caches patterns, but it is good when you reuse a pattern in many places or want a named, documented constant.
re?For fixed strings, use in, str.startswith() or str.replace(). For heavy workloads on untrusted patterns, consider the third-party regex package, or a linear-time engine such as RE2 bindings.
The re module searches, validates, extracts, replaces and splits text with regular expressions. Use raw strings, pick search, match or fullmatch deliberately, name your groups, compile and document complex patterns, and avoid regex for structured formats like HTML or JSON.