The essentials
Quick reference
One focused task per row. Jump to the related section for complete, working examples.
| Use | Syntax | Examples |
|---|---|---|
| Compile a pattern | pattern = re.compile(r'\d{4}-\d{2}-\d{2}') | View examples |
| Search anywhere | match = pattern.search(text) | View examples |
| Match from start | match = pattern.match(text) | View examples |
| Validate the whole string | match = pattern.fullmatch(text) | View examples |
| Capture a group | value = match.group(1) | View examples |
| Named capture | r'(?P<year>\d{4})-(?P<month>\d{2})' | View examples |
| Non-capturing group | r'(?:https?|ftp)://' | View examples |
| Iterate matches | for match in pattern.finditer(text): print(match.span()) | View examples |
| Collect matches | values = pattern.findall(text) | View examples |
| Split by pattern | parts = re.split(r'\s*,\s*', text) | View examples |
| Replace matches | clean = re.sub(r'\s+', ' ', text).strip() | View examples |
| Verbose pattern | pattern = re.compile(r'''...''', re.VERBOSE) | View examples |
| Ignore case | pattern = re.compile(r'error', re.IGNORECASE) | View examples |
Regular expressions describe text patterns, not complete parsers. Use ordinary string methods for literal work, raw strings for readable patterns, fullmatch for whole-value validation, named groups for structured extraction, and bounded inputs for patterns applied to untrusted data.
Step by step
Detailed examples
Choose search, match, or fullmatch intentionally
search scans for the first location, match anchors at position zero, and fullmatch requires complete consumption. Raw Python strings reduce double escaping but cannot end in one unescaped backslash. Compile named patterns reused throughout a module; top-level helpers maintain a small cache.
import re
pattern = re.compile(r'\d{4}-\d{2}-\d{2}')
for value in ['2026-08-12', 'date=2026-08-12']:
print(value, bool(pattern.fullmatch(value))) 2026-08-12 True
date=2026-08-12 FalseName fields that become program data
Capturing parentheses number groups; named groups add readable keys while retaining numbers. Use non-capturing groups when only precedence is needed. Check for None before accessing a match and validate numeric ranges after syntactic extraction.
import re
pattern = re.compile(r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})')
match = pattern.fullmatch('2026-08-12')
print(match.groupdict()) {'year': '2026', 'month': '08', 'day': '12'}Preserve match metadata when positions matter
findall returns strings or tuples depending on capturing groups, which can surprise callers. finditer consistently yields match objects with groups and spans and streams results. re.split includes captured delimiters in output, so use non-capturing groups when delimiters should disappear.
import re
text = 'red, green, blue'
for match in re.finditer(r'[a-z]+', text):
print(match.group(), match.span())
print(re.split(r'\s*,\s*', text)) red (0, 3)
green (5, 10)
blue (12, 16)
['red', 'green', 'blue']Use a function for context-aware replacements
Replacement strings interpret backreferences, while a callable receives each match and returns literal replacement text. subn also reports replacement count. Avoid using regex alone to sanitize HTML, parse programming languages, or enforce security-sensitive grammars.
import re
text = ' Order 4821 '
normalized = re.sub(r'\s+', ' ', text).strip()
redacted, count = re.subn(r'\d', 'X', normalized)
print(redacted)
print(count) Order XXXX
4Make complex patterns reviewable and bounded
VERBOSE permits indentation and comments except inside character classes or escaped spaces. IGNORECASE, MULTILINE, DOTALL, and ASCII change matching semantics and should be local to the pattern. Pathological backtracking can consume excessive time; constrain input length and avoid ambiguous nested repetition for untrusted input.
import re
identifier = re.compile(r'''
[A-Za-z_] # first character
[A-Za-z0-9_]* # remaining characters
''', re.VERBOSE)
print(bool(identifier.fullmatch('user_42')))
print(bool(identifier.fullmatch('42-user'))) True
FalseLocal code tester
Test a named regular expression
Edit a readable pattern, inspect captures and spans, and compare search with fullmatch.
Press Run to load Python locally.
Sources and further reading
References
Authoritative documentation used to verify and expand this cheat sheet.
Help us improve
Found a typo or missing example?
Tell us what would make this cheat sheet clearer, more complete, or more useful.



