Cheat sheetCore Python

Python Regex Cheat Sheet (re Module Quick Reference)

Short answer
Python regular expressions live in the 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

Assume `import re`. Always write patterns as raw strings (`r"..."`) so Python does not process the backslashes.
TaskCodeResult
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 textre.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

TaskCodeResult
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 matchre.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 matchbool(re.fullmatch(r"\d{4}", "2026"))True
Alternation (|)re.findall(r"cat|dog", "cat bird dog")['cat', 'dog']
Not a full matchbool(re.fullmatch(r"\d+", "12ab"))False

Python re module functions cheat sheet

Assume `import re` and `text = "Order 66 shipped on 2026-03-14 to asha@example.com"`. `search()` and `match()` return `None` when nothing matches.
TaskCodeResult
search: first match anywherere.search(r"\d+", text).group()'66'
match: only at the startre.match(r"Order", text).group()'Order'
match fails mid-stringre.match(r"shipped", text)None
findall: all matches as stringsre.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 matchesre.sub(r"\d", "#", text[:8])'Order ##'
sub with a limitre.sub(r"\d", "#", "a1b2c3", count=2)'a#b#c3'
split on a patternre.split(r"[,;]\s*", "a, b;c")['a', 'b', 'c']
subn returns the count toore.subn(r"\d", "#", "a1b2")('a#b#', 2)
compile once, reusere.compile(r"\d+").findall("7 and 42")['7', '42']
fullmatch: entire stringbool(re.fullmatch(r"[a-z]+", "python"))True
Check for no match safelym = re.search(r"zzz", text); m.group() if m else "no match"'no match'

Python regex groups, named groups and lookarounds

TaskCodeResult
Capture groupsre.search(r"(\d{4})-(\d{2})-(\d{2})", text).groups()('2026', '03', '14')
Group by numberre.search(r"(\w+)@(\w+)", text).group(2)'example'
Named groupre.search(r"(?P<year>\d{4})-(?P<month>\d{2})", text).groupdict(){'year': '2026', 'month': '03'}
Non-capturing groupre.findall(r"(?:ab)+", "ababab ab")['ababab', 'ab']
findall with groups returns tuplesre.findall(r"(\w)=(\d)", "a=1 b=2")[('a', '1'), ('b', '2')]
Backreferencere.findall(r"(\w)\1", "book keeper")['o', 'e']
Swap with sub and \2re.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 functionre.sub(r"\d+", lambda m: str(int(m.group()) * 2), "a1 b20")'a2 b40'

Python regex flags cheat sheet

TaskCodeResult
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.Sbool(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 defaultre.findall(r"\w+", "café")['café']
Flags on a compiled patternre.compile(r"cat", re.I).findall("Cat CAT")['Cat', 'CAT']

Python regex patterns for everyday validation

These are practical shapes, not complete validators: real email and phone validation has many more edge cases.
TaskCodeResult
Digits onlybool(re.fullmatch(r"\d+", "12345"))True
Simple email shapebool(re.fullmatch(r"[\w.+-]+@[\w-]+\.[\w.]+", "asha@example.com"))True
Date YYYY-MM-DDre.findall(r"\d{4}-\d{2}-\d{2}", text)['2026-03-14']
Phone like 555-1234bool(re.fullmatch(r"\d{3}-\d{4}", "555-1234"))True
Hashtagsre.findall(r"#(\w+)", "Learn #python and #regex")['python', 'regex']
Extract numbers with decimalsre.findall(r"\d+(?:\.\d+)?", "3.5 kg and 10 g")['3.5', '10']
Collapse repeated spacesre.sub(r" +", " ", "a b c")'a b c'
Trim with a patternre.sub(r"^\s+|\s+$", "", " hi ")'hi'
Words starting with a capitalre.findall(r"\b[A-Z]\w*", "Asha met Ravi in Pune")['Asha', 'Ravi', 'Pune']
Password has a digitbool(re.search(r"\d", "abc1"))True
Count matcheslen(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.

Extract dates and totals from text
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().

Named groups and 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 →