The essentials

Quick reference

One focused task per row. Jump to the related section for complete, working examples.

UseSyntaxExamples
Compile a patternpattern = re.compile(r'\d{4}-\d{2}-\d{2}')View examples
Search anywherematch = pattern.search(text)View examples
Match from startmatch = pattern.match(text)View examples
Validate the whole stringmatch = pattern.fullmatch(text)View examples
Capture a groupvalue = match.group(1)View examples
Named capturer'(?P<year>\d{4})-(?P<month>\d{2})'View examples
Non-capturing groupr'(?:https?|ftp)://'View examples
Iterate matchesfor match in pattern.finditer(text): print(match.span())View examples
Collect matchesvalues = pattern.findall(text)View examples
Split by patternparts = re.split(r'\s*,\s*', text)View examples
Replace matchesclean = re.sub(r'\s+', ' ', text).strip()View examples
Verbose patternpattern = re.compile(r'''...''', re.VERBOSE)View examples
Ignore casepattern = 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

01

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.

Validate an ISO-shaped date
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)))
Output
2026-08-12 True
date=2026-08-12 False
Back to quick reference ↑
02

Name 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.

Extract named date fields
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())
Output
{'year': '2026', 'month': '08', 'day': '12'}
Back to quick reference ↑
03

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.

Find words with positions
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))
Output
red (0, 3)
green (5, 10)
blue (12, 16)
['red', 'green', 'blue']
Back to quick reference ↑
04

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.

Normalize whitespace and redact digits
import re
text = ' Order   4821 '
normalized = re.sub(r'\s+', ' ', text).strip()
redacted, count = re.subn(r'\d', 'X', normalized)
print(redacted)
print(count)
Output
Order XXXX
4
Back to quick reference ↑
05

Make 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.

Readable identifier pattern
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')))
Output
True
False
Back to quick reference ↑

Local code tester

Test a named regular expression

Edit a readable pattern, inspect captures and spans, and compare search with fullmatch.

Runs in your browser
Output
Press Run to load Python locally.

Sources and further reading

References

Authoritative documentation used to verify and expand this cheat sheet.

  1. Python Software Foundationre — Regular expression operationsdocs.python.org
  2. Python Software FoundationRegular Expression HOWTOdocs.python.org

Help us improve

Found a typo or missing example?

Tell us what would make this cheat sheet clearer, more complete, or more useful.

Share feedback