Python Regex Cheat Sheet (re Module Quick Reference)
re module: write the pattern as a raw string, then use re.search(), re.findall(), re.sub() or re.split() to find, extract, replace or split text.Regular expressions describe text patterns. They shine for pulling numbers, dates or emails out of messy strings, but they can be hard to read, so use plain string methods like split() or in when those are enough.
This cheat sheet lists the syntax you need most, each row with its real result on Python 3.13. For a guided introduction read the Python regex lesson.
Python regex character classes and shorthand cheat sheet
| Task | Code | Result |
|---|---|---|
| Digits (\d) | re.findall(r"\d+", "Order 66 on day 14") | ['66', '14'] |
| Non-digit (\D) | re.findall(r"\D+", "a1b22") | ['a', 'b'] |
| Word characters (\w) | re.findall(r"\w+", "hi, there!") | ['hi', 'there'] |
| Whitespace (\s) | re.split(r"\s+", "a b\tc") | ['a', 'b', 'c'] |
| Any character (.) | re.findall(r"c.t", "cat cut c\nt") | ['cat', 'cut'] |
| Character set [abc] | re.findall(r"[aeiou]", "python regex") | ['o', 'e', 'e'] |
| Range [a-z] | re.findall(r"[A-Z][a-z]+", "Asha and Ravi") | ['Asha', 'Ravi'] |
| Negated set [^abc] | re.findall(r"[^aeiou\s]+", "hi you") | ['h', 'y'] |
| Literal dot (escape it) | re.findall(r"\.", "a.b.c") | ['.', '.'] |
| Escape user text | re.escape("1+1=2?") | '1\\+1=2\\?' |
| Word boundary (\b) | re.findall(r"\bcat\b", "cat concat cat.") | ['cat', 'cat'] |
Python regex quantifiers and anchors cheat sheet
| Task | Code | Result |
|---|---|---|
| Zero or more (*) | re.findall(r"ab*", "a ab abbb") | ['a', 'ab', 'abbb'] |
| One or more (+) | re.findall(r"ab+", "a ab abbb") | ['ab', 'abbb'] |
| Optional (?) | re.findall(r"colou?r", "color colour") | ['color', 'colour'] |
| Exactly n ({3}) | re.findall(r"\d{3}", "12 345 6789") | ['345', '678'] |
| Range of repeats ({2,4}) | re.findall(r"\d{2,4}", "1 22 33333") | ['22', '3333'] |
| Greedy match | re.findall(r"<.+>", "<a><b>") | ['<a><b>'] |
| Lazy match (+?) | re.findall(r"<.+?>", "<a><b>") | ['<a>', '<b>'] |
| Start of string (^) | bool(re.match(r"^py", "python")) | True |
| End of string ($) | bool(re.search(r"ing$", "coding")) | True |
| Whole string match | bool(re.fullmatch(r"\d{4}", "2026")) | True |
| Alternation (|) | re.findall(r"cat|dog", "cat bird dog") | ['cat', 'dog'] |
| Not a full match | bool(re.fullmatch(r"\d+", "12ab")) | False |
Python re module functions cheat sheet
| Task | Code | Result |
|---|---|---|
| search: first match anywhere | re.search(r"\d+", text).group() | '66' |
| match: only at the start | re.match(r"Order", text).group() | 'Order' |
| match fails mid-string | re.match(r"shipped", text) | None |
| findall: all matches as strings | re.findall(r"\d+", text) | ['66', '2026', '03', '14'] |
| finditer: match objects with positions | [m.span() for m in re.finditer(r"\d+", text)] | [(6, 8), (20, 24), (25, 27), (28, 30)] |
| sub: replace matches | re.sub(r"\d", "#", text[:8]) | 'Order ##' |
| sub with a limit | re.sub(r"\d", "#", "a1b2c3", count=2) | 'a#b#c3' |
| split on a pattern | re.split(r"[,;]\s*", "a, b;c") | ['a', 'b', 'c'] |
| subn returns the count too | re.subn(r"\d", "#", "a1b2") | ('a#b#', 2) |
| compile once, reuse | re.compile(r"\d+").findall("7 and 42") | ['7', '42'] |
| fullmatch: entire string | bool(re.fullmatch(r"[a-z]+", "python")) | True |
| Check for no match safely | m = re.search(r"zzz", text); m.group() if m else "no match" | 'no match' |
Python regex groups, named groups and lookarounds
| Task | Code | Result |
|---|---|---|
| Capture groups | re.search(r"(\d{4})-(\d{2})-(\d{2})", text).groups() | ('2026', '03', '14') |
| Group by number | re.search(r"(\w+)@(\w+)", text).group(2) | 'example' |
| Named group | re.search(r"(?P<year>\d{4})-(?P<month>\d{2})", text).groupdict() | {'year': '2026', 'month': '03'} |
| Non-capturing group | re.findall(r"(?:ab)+", "ababab ab") | ['ababab', 'ab'] |
| findall with groups returns tuples | re.findall(r"(\w)=(\d)", "a=1 b=2") | [('a', '1'), ('b', '2')] |
| Backreference | re.findall(r"(\w)\1", "book keeper") | ['o', 'e'] |
| Swap with sub and \2 | re.sub(r"(\w+) (\w+)", r"\2 \1", "hello world") | 'world hello' |
| Lookahead (?=) | re.findall(r"\w+(?=@)", text) | ['asha'] |
| Negative lookahead (?!) | re.findall(r"\b\d+\b(?!-)", "12-34 56") | ['34', '56'] |
| Lookbehind (?<=) | re.findall(r"(?<=\$)\d+", "cost $45 and $7") | ['45', '7'] |
| Replace using a function | re.sub(r"\d+", lambda m: str(int(m.group()) * 2), "a1 b20") | 'a2 b40' |
Python regex flags cheat sheet
| Task | Code | Result |
|---|---|---|
| Ignore case (re.I) | re.findall(r"py", "Py PY py", re.I) | ['Py', 'PY', 'py'] |
| Multiline anchors (re.M) | re.findall(r"^\w+", "one\ntwo", re.M) | ['one', 'two'] |
| Dot matches newline (re.S) | bool(re.search(r"a.b", "a\nb", re.S)) | True |
| Without re.S | bool(re.search(r"a.b", "a\nb")) | False |
| Verbose patterns (re.X) | re.search(r"""\d+ # digits""", "x42", re.X).group() | '42' |
| Inline flag (?i) | re.findall(r"(?i)py", "Py py") | ['Py', 'py'] |
| Combine flags with | | re.findall(r"^py", "Py\npy", re.I | re.M) | ['Py', 'py'] |
| ASCII-only \w (re.A) | re.findall(r"\w+", "café", re.A) | ['caf'] |
| Unicode \w by default | re.findall(r"\w+", "café") | ['café'] |
| Flags on a compiled pattern | re.compile(r"cat", re.I).findall("Cat CAT") | ['Cat', 'CAT'] |
Python regex patterns for everyday validation
| Task | Code | Result |
|---|---|---|
| Digits only | bool(re.fullmatch(r"\d+", "12345")) | True |
| Simple email shape | bool(re.fullmatch(r"[\w.+-]+@[\w-]+\.[\w.]+", "asha@example.com")) | True |
| Date YYYY-MM-DD | re.findall(r"\d{4}-\d{2}-\d{2}", text) | ['2026-03-14'] |
| Phone like 555-1234 | bool(re.fullmatch(r"\d{3}-\d{4}", "555-1234")) | True |
| Hashtags | re.findall(r"#(\w+)", "Learn #python and #regex") | ['python', 'regex'] |
| Extract numbers with decimals | re.findall(r"\d+(?:\.\d+)?", "3.5 kg and 10 g") | ['3.5', '10'] |
| Collapse repeated spaces | re.sub(r" +", " ", "a b c") | 'a b c' |
| Trim with a pattern | re.sub(r"^\s+|\s+$", "", " hi ") | 'hi' |
| Words starting with a capital | re.findall(r"\b[A-Z]\w*", "Asha met Ravi in Pune") | ['Asha', 'Ravi', 'Pune'] |
| Password has a digit | bool(re.search(r"\d", "abc1")) | True |
| Count matches | len(re.findall(r"o", "foo boo")) | 4 |
Python regex tips: raw strings, greedy matching and when to avoid regex
Always prefix patterns with r (r"\d+") so backslashes reach the regex engine unchanged. Quantifiers are greedy by default, so <.+> grabs as much as it can; add ? (<.+?>) for the shortest match. re.match() only checks the start of the string, while re.search() looks anywhere and re.fullmatch() demands the whole string.
Avoid regex for structured formats: use the json module for JSON and csv for CSV, and use string methods for fixed separators.
Examples you can run
Press Run, then edit the code and run it again.
Extract dates and totals from text
findall returns a list of every match; groups turn each match into a tuple.
import re
log = "2026-03-14 paid 450, 2026-03-15 paid 120"
print(re.findall(r"\d{4}-\d{2}-\d{2}", log))
print(re.findall(r"(\d{4})-(\d{2})-\d{2} paid (\d+)", log))Expected output['2026-03-14', '2026-03-15']
[('2026', '03', '450'), ('2026', '03', '120')]
Named groups and sub()
Name the parts of a match, then reformat the text with sub().
import re
m = re.search(r"(?P<day>\d{2})/(?P<month>\d{2})/(?P<year>\d{4})", "Due 05/11/2026")
print(m.group("year"), m.group("month"), m.group("day"))
print(re.sub(r"(\d{2})/(\d{2})/(\d{4})", r"\3-\2-\1", "Due 05/11/2026"))Expected output2026 11 05
Due 2026-11-05
Python Regex Cheat Sheet (re Module Quick Reference): questions people ask
What is the difference between re.match and re.search?
re.match() only matches at the beginning of the string, while re.search() finds the first match anywhere in it. Both return None when nothing matches.
Why should I use raw strings for regex in Python?
Raw strings (r"...") keep backslashes as typed, so r"\d" reaches the regex engine as \d. Without the r, sequences like \b are turned into other characters by Python first.
How do I get all matches with re in Python?
Use re.findall(pattern, text) for a list of strings, or re.finditer(pattern, text) for match objects that also give positions with .span().
Keep learning
Step-by-step lessons:
Python Regular Expressions (regex)Python StringsPython String Methods
Related:
Python String Cheat Sheet: Methods and FormattingPython Cheat Sheet (Python 3.13 Quick Reference)How to Check if a String Contains a Substring in PythonPython String split() MethodHow to Split a String into Words in Python
More in core python:
Python Cheat Sheet (Python 3.13 Quick Reference)Python String Cheat Sheet: Methods and FormattingPython List Cheat Sheet: Methods and ExamplesPython Dictionary Cheat Sheet: Methods and ExamplesPython Control Flow Cheat Sheet: if, for, while, matchPython Functions Cheat Sheet: def, args, lambda, scopePython OOP Cheat Sheet: Classes, Inheritance, Dunder MethodsPython File Handling Cheat Sheet: open, read, write, CSV, JSON See all →