Back to Home 22 lessons Pyodide ready

Python Regex
Regular Expressions & Pattern Matching

Master Python's re module: pattern syntax, match/search, findall/finditer, substitution, groups, lookaheads, and flags. 22 interactive lessons with runnable code β€” crafted by @PoeticGlenn.

What you will learn

Everything about Python's re module β€” the standard toolkit for regular expressions. Learn pattern syntax (character classes, quantifiers, anchors, alternation), the core functions (match, search, findall, finditer, sub, split), capturing and named groups, lookaheads and lookbehinds, and flags like IGNORECASE, MULTILINE, DOTALL, and VERBOSE. Each concept is broken down step-by-step with interactive code examples from @PoeticGlenn.

Why Regular Expressions Are a Superpower

Regular expressions are a mini-language for describing text patterns. With a single line of regex, you can validate emails, extract phone numbers from logs, reformat dates, or strip HTML tags β€” tasks that would otherwise take dozens of lines of string manipulation. Python's re module (part of the standard library) provides a complete, fast regex engine. Whether you're cleaning data, parsing logs, validating user input, or building a search feature, regex is the tool you'll reach for again and again. This curriculum, designed by @PoeticGlenn, teaches you regex from the ground up with clear, runnable examples.

Search & Match

Find patterns anywhere in text, with precise control over what counts as a match.

Extract & Replace

Pull out emails, URLs, or numbers β€” or substitute patterns across huge documents.

Validate Input

Enforce formats for emails, phone numbers, passwords, and dates β€” safely and clearly.

"Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems." β€” Jamie Zawinski 🐍 (But with care, regex is still a superpower.)

Regex Is Used Everywhere

Web scraping, log analysis, data cleaning, form validation, log parsing, config file processing, search engines β€” regex appears in nearly every domain. Once you learn it, you'll spot patterns worth automating everywhere. This curriculum, curated by @PoeticGlenn, focuses on the patterns you'll actually use β€” with careful attention to correctness and performance.

🧹 Data Cleaning

Strip whitespace, normalize formats, remove duplicates, and fix typos in bulk.

πŸ“œ Log Analysis

Extract IP addresses, timestamps, error codes, and user agents from log lines.

πŸ” Input Validation

Check that emails, phone numbers, and passwords match expected formats before saving.

πŸ•·οΈ Web Scraping

Find and extract URLs, prices, titles, and structured data from raw HTML.

@PoeticGlenn says: "Regex is like a Swiss Army knife β€” once you know it, you keep finding uses for it."

A Universal Language for Text

Regular expressions exist in virtually every programming language and tool β€” from grep, sed, and awk on the command line, to JavaScript, Ruby, Java, and Go. Python's re module follows the same broad syntax, so the skills you learn here transfer everywhere. Understanding regex, as taught by @PoeticGlenn, means understanding the pattern language that underpins search, validation, and text processing worldwide.

Universal Syntax

Almost every language follows the same regex rules β€” learn once, use everywhere.

Command-Line Power

grep, sed, awk, and vim all use regex β€” master it and your terminal becomes a tool factory.

Concise & Fast

A single pattern replaces dozens of lines of manual string checking, with C-level speed.

"Text is the most common data format β€” and regex is its fastest reader."

🧩 Regex Basics β€” Character Classes & Quantifiers

The building blocks of every pattern you'll write.

πŸ“ 1.1 Literal Characters & Wildcard

Most characters match themselves. The dot . matches any single character.

Step-by-step explanation:

  • Step 1: Import re.
  • Step 2: Use re.findall() to see all matches.
  • Step 3: Notice . matches any single character.
python
import re

text = "cat bat hat mat"

# Literal pattern
print("'cat':", re.findall("cat", text))

# Dot wildcard
print("'.at':", re.findall(".at", text))

# Dot matches any char
print("'c.t':", re.findall("c.t", text))
πŸ’‘ . does not match a newline by default. Use the DOTALL flag to change that.

πŸ“ 1.2 Character Classes [...]

Match any one of several characters using square brackets.

Step-by-step explanation:

  • Step 1: Use [abc] to match any of a, b, c.
  • Step 2: Use [a-z] for a range.
  • Step 3: Use [^...] to negate the class.
python
import re

text = "The year 2026 has 12 months and 365 days."

# Digits only
print("digits:", re.findall(r"\d+", text))

# Multiple digits
print("[0-9]+:", re.findall(r"[0-9]+", text))

# Letters only
print("[a-z]+:", re.findall(r"[a-z]+", text))

# Alternation of vowels
print("[aeiou]:", re.findall(r"[aeiou]", "hello world", re.I))

# Negated class β€” anything not a digit
print("[^0-9]+:", re.findall(r"[^0-9]+", "a1b2c3"))

πŸ“ 1.3 Common Character Shorthand

Memorize these shorthand classes β€” you'll use them constantly.

PatternMatchesExample
\dDigit[0-9]
\DNon-digit[^0-9]
\wWord char[a-zA-Z0-9_]
\WNon-word[^a-zA-Z0-9_]
\sWhitespacespace, \t, \n
\SNon-whitespaceanything else
.Any char (except newline)
python
import re

text = "Order #A12345 shipped on 2026-06-30"

print("\\d+:", re.findall(r"\d+", text))
print("\\w+:", re.findall(r"\w+", text))
print("\\S+:", re.findall(r"\S+", text))
print("\\s+:", re.findall(r"\s+", text))
✨ Always use raw strings r"..." for regex patterns β€” otherwise Python interprets \d as an escape sequence.

πŸ“ 1.4 Quantifiers * + ? {n,m}

Control how many times a character or group repeats.

QuantifierMeaningExample
*0 or morea*
+1 or morea+
?0 or 1a?
{n}Exactly na{3}
{n,}n or morea{3,}
{n,m}Between n and ma{2,4}
python
import re

print("a*:  ", re.findall(r"ab*c", "ac abc abbc abbbc"))
print("a+:  ", re.findall(r"ab+c", "ac abc abbc abbbc"))
print("a?:  ", re.findall(r"ab?c", "ac abc abbc"))
print("{2,3}:", re.findall(r"ab{2,3}c", "abc abbc abbbc abbbbc"))
print("{3}: ", re.findall(r"\d{3}", "1 12 123 1234 12345"))
πŸ’‘ Quantifiers are greedy by default β€” they match as much as possible. Add ? after to make them lazy: *?, +?, ??, {n,m}?.

πŸ“ 1.5 Anchors ^ $ \b

Match positions rather than characters.

Step-by-step explanation:

  • Step 1: ^ matches the start of the string (or line with MULTILINE).
  • Step 2: $ matches the end of the string.
  • Step 3: \b matches a word boundary.
python
import re

text = "hello world hello"

print("^hello:", re.findall(r"^hello", text))
print("hello$:", re.findall(r"hello$", text))
print("\\bworld\\b:", re.findall(r"\bworld\b", text))
print("\\bhello\\b:", re.findall(r"\bhello\b", text))

# MULTILINE demo
multiline = "start\nmiddle\nend"
print("\nstarts:", re.findall(r"^\w+", multiline, re.M))
print("ends:  ", re.findall(r"\w+$", multiline, re.M))
⚠️ ^ and $ are by default anchored to start/end of the entire string. Use re.M for per-line anchors.

πŸ“‹ findall & finditer β€” Get All Matches

Extract every match, not just the first.

πŸ“ 3.1 re.findall()

Returns a list of all matches as strings (or tuples if the pattern has groups).

Step-by-step explanation:

  • Step 1: Call re.findall(pattern, text).
  • Step 2: Returns a list of strings.
  • Step 3: With groups, returns a list of tuples.
python
import re

text = "Emails: alice@example.com, bob@test.org, carol@site.net"

emails = re.findall(r"\S+@\S+", text)
print("Emails:", emails)
print("Count:  ", len(emails))

# Numbers
nums = re.findall(r"\d+", "Order 123, item 456, qty 789")
print("\nNumbers:", nums)

# With groups β€” returns tuples
pairs = re.findall(r"(\w+)@(\w+)", text)
print("\nPairs:", pairs)
πŸ’‘ If the pattern has one capture group, findall() returns a list of strings; with multiple groups, a list of tuples.

πŸ“ 3.2 re.finditer()

Returns an iterator of Match objects β€” better for large inputs or when you need positions.

Step-by-step explanation:

  • Step 1: Use re.finditer(pattern, text).
  • Step 2: Iterate over the Match objects.
  • Step 3: Access .group(), .start(), .end().
python
import re

text = "IDs: A101, B202, C303"

for m in re.finditer(r"[A-Z](\d+)", text):
    print(f"Match: {m.group()}, digits: {m.group(1)}, position: {m.start()}")
✨ finditer() is lazy β€” it yields matches one at a time, saving memory for large files.

πŸ”„ Substitution β€” re.sub() & re.split()

Replace matched patterns or split strings using regex.

πŸ“ 4.1 re.sub() β€” Replace Matches

Replace every match with a string or function result.

Step-by-step explanation:

  • Step 1: Call re.sub(pattern, replacement, text).
  • Step 2: Use \1, \2 to reference captured groups.
  • Step 3: Limit replacements with count=n.
python
import re

text = "The price is $100 and the discount is $20"

# Simple replacement
masked = re.sub(r"\d+", "N", text)
print("Masked:", masked)

# With groups β€” reorder date
date = "2026-06-30"
us = re.sub(r"(\d{4})-(\d{2})-(\d{2})", r"\2/\3/\1", date)
print("\nUS date:", us)

# Limit replacements
limited = re.sub(r"\d+", "X", text, count=1)
print("\nLimited:", limited)

# Replace with function
def double(match):
    return str(int(match.group()) * 2)

print("\nDoubled:", re.sub(r"\d+", double, text))
πŸ’‘ For complex replacements, passing a function is often cleaner than juggling backreferences in the replacement string.

πŸ“ 4.2 re.split() β€” Split on Pattern

Split a string wherever the pattern matches.

Step-by-step explanation:

  • Step 1: Call re.split(pattern, text).
  • Step 2: Split on multiple delimiters at once.
  • Step 3: Optionally limit splits with maxsplit.
python
import re

# Split on multiple delimiters
text = "apple,banana;cherry orange"
parts = re.split(r"[,;\s]+", text)
print("Parts:", parts)

# Split on digits
print("\nSplit on digits:", re.split(r"\d+", "a1b22c333d"))

# Limit splits
print("\nMaxsplit=2:", re.split(r"\s+", "a b c d e", maxsplit=2))
✨ re.split() is much more flexible than str.split() β€” it handles multiple delimiters at once.

πŸ“¦ Groups β€” Capture & Reuse Subpatterns

Extract substrings and organize complex patterns.

πŸ“ 5.1 Numbered Groups (...)

Parentheses capture substrings you can reference later.

Step-by-step explanation:

  • Step 1: Wrap parts of the pattern in (...).
  • Step 2: Access with .group(1), .group(2).
  • Step 3: Use .groups() for a tuple of all groups.
python
import re

text = "John Smith, 30 years old"
m = re.search(r"(\w+)\s+(\w+),\s+(\d+)", text)

if m:
    print("Whole match:", m.group(0))
    print("First name: ", m.group(1))
    print("Last name:  ", m.group(2))
    print("Age:        ", m.group(3))
    print("All groups: ", m.groups())
πŸ’‘ .group(0) is the entire match. .group(1) is the first parenthesized group.

πŸ“ 5.2 Named Groups (?P<name>...)

Give groups names for clarity and easier access.

Step-by-step explanation:

  • Step 1: Use (?P<name>pattern) syntax.
  • Step 2: Access with .group("name") or .groupdict().
python
import re

text = "2026-06-30"
m = re.search(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})", text)

if m:
    print("Year:  ", m.group("year"))
    print("Month: ", m.group("month"))
    print("Day:   ", m.group("day"))
    print("Dict:  ", m.groupdict())
✨ Named groups are self-documenting β€” use them for readability, especially in complex patterns.

πŸ“ 5.3 Non-Capturing Groups (?:...)

Group without capturing β€” useful for applying quantifiers without affecting group numbering.

Step-by-step explanation:

  • Step 1: Use (?:...) instead of (...).
  • Step 2: Apply quantifiers to the whole group.
  • Step 3: Groups don't appear in .groups().
python
import re

# Match repeated words without capturing each "ha"
text = "hahaha hehehe hihihi"
print("Captured:    ", re.findall(r"(ha)+", text))
print("Non-captured:", re.findall(r"(?:ha)+", text))

# Alternation inside a group
pattern = r"(?:cat|dog)s?"
print("\nAnimals:", re.findall(pattern, "cat cats dog dogs"))

πŸš€ Advanced β€” Lookaheads, Lookbehinds & Backreferences

Power-user patterns for sophisticated matching.

πŸ“ 6.1 Lookaheads (?=...) and (?!...)

Assert that a pattern follows without consuming characters.

Step-by-step explanation:

  • Step 1: (?=...) is a positive lookahead.
  • Step 2: (?!...) is a negative lookahead.
  • Step 3: The lookahead characters aren't included in the match.
python
import re

text = "apple pie, apple cake, apple juice"

# Match "apple" only if followed by " pie"
print("Before pie:", re.findall(r"apple(?= pie)", text))

# Match "apple" NOT followed by " pie"
print("Not pie:   ", re.findall(r"apple(?! pie)", text))

# Password validator: 8+ chars, at least one digit
password = "abc12345"
if re.search(r"^(?=.*\d).{8,}$", password):
    print("\nPassword valid")
else:
    print("\nPassword invalid")
πŸ’‘ Lookaheads don't consume characters β€” perfect for validation that requires multiple conditions.

πŸ“ 6.2 Lookbehinds (?<=...) and (?<!...)

Assert that a pattern precedes the match.

Step-by-step explanation:

  • Step 1: (?<=...) requires the pattern to appear before.
  • Step 2: (?<!...) requires it NOT to appear before.
  • Step 3: Lookbehinds must be fixed-length.
python
import re

text = "USD100 EUR200 USD300"

# Match amounts ONLY after USD
print("USD amounts:", re.findall(r"(?<=USD)\d+", text))

# Match amounts NOT after USD
print("Non-USD:    ", re.findall(r"(?<!USD)\d+", text))

# Extract the currency code before numbers
print("\nCurrency codes:", re.findall(r"[A-Z]{3}(?=\d)", text))

πŸ“ 6.3 Backreferences \1, \2

Match the same text that a previous group captured.

Step-by-step explanation:

  • Step 1: Capture a word with (\w+).
  • Step 2: Use \1 to require the same word again.
  • Step 3: Find repeated words with r"\b(\w+)\s+\1\b".
python
import re

# Find doubled words
text = "the the cat sat sat on on the mat"
repeats = re.findall(r"\b(\w+)\s+\1\b", text)
print("Doubled words:", repeats)

# Rearrange with backreferences
date = "2026-06-30"
fixed = re.sub(r"(\d{4})-(\d{2})-(\d{2})", r"\3.\2.\1", date)
print("\nRearranged:", fixed)

# Match a quoted string (same quote char)
quoted = re.findall(r"(['\"]).*?\1", "'hello' and \"world\"")
print("\nQuoted strings:", quoted)
⚠️ Backreferences only work within the same pattern β€” they can't match text from a previous call.

🚩 Flags β€” Change Pattern Behavior

Global modifiers that adjust how regex matches.

πŸ“ 7.1 re.IGNORECASE (re.I)

Match regardless of uppercase/lowercase.

Step-by-step explanation:

  • Step 1: Pass re.I as a flag.
  • Step 2: Both "Hello" and "HELLO" match "hello".
python
import re

text = "Hello HELLO hello HeLLo"

print("No flag:     ", re.findall("hello", text))
print("re.I flag:   ", re.findall("hello", text, re.I))
print("(?i) inline: ", re.findall("(?i)hello", text))
πŸ’‘ (?i) at the start of a pattern is equivalent to re.I β€” useful when you can't pass flags (e.g., inside config files).

πŸ“ 7.2 re.MULTILINE (re.M)

Make ^ and $ match line starts/ends instead of string boundaries.

Step-by-step explanation:

  • Step 1: Pass re.M.
  • Step 2: ^ matches after each newline.
  • Step 3: $ matches before each newline.
python
import re

text = "first\nsecond\nthird"

print("No flag:   ", re.findall(r"^\w+", text))
print("re.M flag: ", re.findall(r"^\w+", text, re.M))
print("ends:      ", re.findall(r"\w+$", text, re.M))

πŸ“ 7.3 re.DOTALL (re.S) & re.VERBOSE (re.X)

DOTALL makes . match newlines. VERBOSE allows comments in patterns.

Step-by-step explanation:

  • Step 1: re.S lets . cross newlines.
  • Step 2: re.X ignores whitespace and # comments in patterns.
  • Step 3: Combine flags with |.
python
import re

# DOTALL β€” match across newlines
html = "<div>\ncontent\n</div>"
print("No DOTALL:", re.findall(r"<div>.*</div>", html))
print("DOTALL:   ", re.findall(r"<div>.*</div>", html, re.S))

# VERBOSE β€” readable complex patterns
pattern = r"""
    \b          # word boundary
    \w+         # one or more word chars
    @           # at sign
    \w+         # domain
    \.          # literal dot
    \w+         # TLD
    \b          # word boundary
"""
text = "Contact: alice@example.com for info"
print("\nEmails:", re.findall(pattern, text, re.X))
✨ re.VERBOSE is your friend for long patterns β€” break them into readable, commented lines.

πŸ“ 7.4 Compiled Patterns β€” re.compile()

Compile once, reuse many times β€” faster and cleaner for repeated matching.

Step-by-step explanation:

  • Step 1: Call re.compile(pattern, flags).
  • Step 2: Call methods on the compiled object directly.
  • Step 3: Reuse across many strings.
python
import re

# Compile once
email_re = re.compile(r"\b[\w.]+@[\w.]+\.\w+\b")

# Use many times
texts = [
    "alice@example.com sent a message",
    "contact bob@test.org for support",
    "no email here",
]

for t in texts:
    matches = email_re.findall(t)
    print(f"{t!r}: {matches}")

# Access the pattern and flags
print("\nPattern:", email_re.pattern)
print("Flags:  ", email_re.flags)
πŸ’‘ Python caches recently used patterns automatically, but explicit compile() is clearer and slightly faster for hot loops.

❓ Frequently Asked Questions β€” Python Regex

Common questions about regular expressions in Python.

What's the difference between match, search, and fullmatch?

+

match() checks only the start of the string. search() scans the entire string for the first match. fullmatch() requires the pattern to match the entire string. Use fullmatch() for validation, search() for finding, match() only when you specifically need start-anchoring.

Why do I need to use raw strings r"..." for patterns?

+

In a regular string, "\d" is just "d" because Python interprets \d as an unknown escape. With r"\d", the backslash is preserved literally. Always use raw strings for regex β€” it prevents subtle bugs, especially with backslashes.

What's the difference between greedy and non-greedy matching?

+

By default, quantifiers (*, +, {n,m}) are greedy β€” they match as much as possible. Add a ? to make them lazy: *?, +?, ??, {n,m}?. Lazy matching is crucial when extracting content between delimiters.

How do I match a literal dot . or other special characters?

+

Escape special characters with a backslash: \., \*, \+, \?, \(, \), \[, \], \{, \}, \^, \$, \|, \\. Or use re.escape(string) to escape a whole string automatically.

What is a "catastrophic backtracking" regex?

+

Patterns with nested quantifiers like (a+)+ can cause exponential backtracking on non-matching input, freezing your program. Avoid nested quantifiers on the same character class. Test with long inputs; if it hangs, restructure or use re2/regex modules.

How do I capture multiple groups in findall()?

+

If the pattern has multiple groups, findall() returns a list of tuples, one per match. If there's one group, it returns a list of strings. If there are no groups, it returns a list of full match strings. Use finditer() when you need per-match position or group access.

How do I do case-insensitive matching?

+

Pass re.IGNORECASE (or re.I) as a flag: re.findall("hello", text, re.I). Or prefix the pattern with (?i): re.findall("(?i)hello", text). Both are equivalent.

Why does re.search() return None even though the pattern is there?

+

Common causes: (1) forgot to use a raw string and the backslashes got mangled; (2) pattern anchors ^/$ behave unexpectedly without re.M; (3) uppercase vs. lowercase without re.I; (4) escaped characters like \. vs .. Print your pattern with repr() to verify it's what you expect.

How do I match across multiple lines?

+

Use re.DOTALL (re.S) to make . match newlines, and re.MULTILINE (re.M) to make ^/$ match line boundaries instead of string boundaries. Combine both with re.S | re.M if you need both behaviors.

πŸ’› You've Mastered Python Regex

From basic character classes to lookaheads and backreferences, you now have a full toolkit for matching patterns in text. You can validate input, extract structured data, clean up messy strings, and build search features with confidence.

This curriculum, crafted by @PoeticGlenn, gives you the foundation for every text-processing task in Python. The patterns you've learned transfer directly to other languages, tools like grep and sed, and every text-based workflow you'll ever touch.

22 lessons 25+ code examples 1.0k+ learners

"Regex is a language of its own β€” once you speak it, text becomes queryable." β€” Glenn Junsay Pansensoy (@PoeticGlenn)