Python Reference ยท Standard Library: Math, Data and Text
The re module
Reference for Python's re module: search, match, fullmatch, findall, finditer, sub, split, compile, groups, flags, lookarounds and common regex pitfalls.
The re module finds, extracts and rewrites text using regular expressions: compact patterns that describe sets of strings. Use it when plain string methods such as in, startswith() or split() are not flexible enough, for example to find every date in a document or validate that a code has the shape AB-1234.
Patterns are ordinary strings, but you should almost always write them as raw strings (r"\d+") so Python does not interpret the backslashes first. Functions return match objects (or None when nothing matches), which carry the matched text, its position and any captured groups.
import re m = re.search(r"(\d{4})-(\d{2})", "released 2030-07-14") print(m.group(1), m.group(2)) # 2030 07
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Main functions
| Function | Returns |
|---|---|
re.search(pattern, string, flags=0) |
The first match anywhere in the string, or None. |
re.match(pattern, string, flags=0) |
A match only at the start of the string, or None. |
re.fullmatch(pattern, string, flags=0) |
A match only if the whole string matches, or None. |
re.findall(pattern, string, flags=0) |
A list of all non-overlapping matches: strings, or tuples if the pattern has several groups. |
re.finditer(pattern, string, flags=0) |
An iterator of match objects. |
re.sub(pattern, repl, string, count=0, flags=0) |
A new string with matches replaced. repl is a template (\1, \g<name>) or a function. |
re.subn(...) |
Like sub, but returns (new_string, number_of_replacements). |
re.split(pattern, string, maxsplit=0, flags=0) |
A list of pieces; captured groups are included in the list. |
re.compile(pattern, flags=0) |
A reusable Pattern object with the same methods. |
re.escape(text) |
Escapes special characters so text matches literally. |
Match object
| Member | Description |
|---|---|
m.group() / m.group(n) / m.group("name") |
Whole match, numbered group or named group (None if the group did not participate). |
m.groups() / m.groupdict() |
Tuple of all groups; dict of named groups. |
m.start(), m.end(), m.span() |
Positions in the original string. |
m[n] |
Shortcut for m.group(n). |
Flags
| Flag | Short | Effect |
|---|---|---|
re.IGNORECASE |
re.I |
Case-insensitive matching. |
re.MULTILINE |
re.M |
^ and $ match at every line. |
re.DOTALL |
re.S |
. also matches newlines. |
re.VERBOSE |
re.X |
Ignore whitespace and allow # comments in the pattern. |
re.ASCII |
re.A |
\w, \d, \s match ASCII only (they are Unicode-aware by default for str). |
Usage notes
matchvssearchvsfullmatch.matchis anchored at the start only;fullmatchat both ends. Beginners often expectmatchto find text in the middle of a string.- Always check for
Nonebefore calling.group(); otherwise you getAttributeError: 'NoneType' object has no attribute 'group'. - Use raw strings.
"\b"is a backspace character in a normal string but a word boundary inr"\b". - Quantifiers are greedy by default (
.+takes as much as possible). Add?(.+?) for the shortest match. findallreturns groups, not matches, when the pattern has capture groups. Use(?:...)for groups you do not want captured, or usefinditer.- Compile only matters for reuse. Module functions cache recent patterns, so
re.compileis mainly for readability and flags. - Catastrophic backtracking. Nested quantifiers such as
(a+)+$can take exponential time on crafted input. Never run untrusted patterns, and be careful with untrusted text. - Do not parse HTML or nested structures with regular expressions; use a real parser.
- Python 3.11 added possessive quantifiers (
a++) and atomic groups ((?>...)). Python 3.13 addedre.PatternErroras the preferred name ofre.error.