100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

Python Regex Cheat Sheet

Python Regex Cheat Sheet

Python's re module covering core matching functions, common metacharacters, capture groups, and compiled patterns with flags.

1 PageIntermediateMar 28, 2026

Core re Functions

The most-used entry points into the re module.

python
import rere.match(r"\d+", "123abc")      # matches only at the startre.search(r"\d+", "abc123")     # matches anywhere in the stringre.findall(r"\d+", "a1b22c333") # ['1', '22', '333']re.sub(r"\d+", "#", "a1b22c")   # 'a#b#c're.split(r"\s+", "a  b   c")    # ['a', 'b', 'c']

Common Metacharacters & Classes

Building blocks for constructing patterns.

  • \d / \D- digit / non-digit character
  • \w / \W- word character [a-zA-Z0-9_] / non-word character
  • \s / \S- whitespace / non-whitespace character
  • ^ / $- start of string (or line) / end of string (or line)
  • . - any character except newline (unless re.DOTALL)
  • * / + / ?- zero-or-more / one-or-more / zero-or-one repetition
  • {m,n}- between m and n repetitions of the preceding token
  • [abc] / [^abc]- character class matching / negated character class

Groups & Named Groups

Capturing and extracting parts of a match.

python
m = re.match(r"(\d{4})-(\d{2})-(\d{2})", "2024-01-15")m.group(0)   # '2024-01-15' (whole match)m.group(1)   # '2024'm.groups()   # ('2024', '01', '15')m = re.match(r"(?P<year>\d{4})-(?P<month>\d{2})", "2024-01")m.group("year")   # '2024'm.groupdict()      # {'year': '2024', 'month': '01'}

Compiling Patterns & Flags

Reusing patterns efficiently and modifying match behavior.

python
pattern = re.compile(r"\d+")pattern.findall("A1 b2")   # ['1', '2']re.search(r"hello", "HELLO WORLD", re.IGNORECASE)re.findall(r"^\w+", "line1\nline2", re.MULTILINE)re.match(r"a.b", "a\nb", re.DOTALL)  # . also matches newline
Pro Tip

Always use raw strings (r"...") for regex patterns — without the r prefix, Python's own backslash escaping (like \d being interpreted before the regex engine sees it) can silently produce a different pattern than the one you wrote.

Was this cheat sheet helpful?

Explore Topics

#PythonRegex#PythonRegexCheatSheet#Programming#Intermediate#CoreReFunctions#CommonMetacharactersClasses#GroupsNamedGroups#CompilingPatternsFlags#Functions#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech

Professional Web Designing Services

  • Responsive Websites
  • E-commerce Solutions
  • SEO Friendly Design
  • Fast & Secure
  • Support & Maintenance
Get a Free Quote

Share this Cheat Sheet