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.
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."
π Table of Contents
Jump to any section β all entries are equal size
π§© 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.
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.
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.
| Pattern | Matches | Example |
|---|---|---|
\d | Digit | [0-9] |
\D | Non-digit | [^0-9] |
\w | Word char | [a-zA-Z0-9_] |
\W | Non-word | [^a-zA-Z0-9_] |
\s | Whitespace | space, \t, \n |
\S | Non-whitespace | anything else |
. | Any char (except newline) |
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))
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.
| Quantifier | Meaning | Example |
|---|---|---|
* | 0 or more | a* |
+ | 1 or more | a+ |
? | 0 or 1 | a? |
{n} | Exactly n | a{3} |
{n,} | n or more | a{3,} |
{n,m} | Between n and m | a{2,4} |
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"))
? 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:
\bmatches a word boundary.
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.π― match vs search
The two main matching functions β and when to use each.
π 2.1 re.match() β Anchor at Start
match() only matches at the beginning of the string.
Step-by-step explanation:
- Step 1: Call
re.match(pattern, text). - Step 2: Returns a
Matchobject orNone. - Step 3: Check with
if m:.
import re text = "hello world" m = re.match(r"hello", text) print("Match hello:", m) print("Group: ", m.group() if m else None) m2 = re.match(r"world", text) print("\nMatch world:", m2) # Match vs search print("\nsearch world:", re.search(r"world", text))
re.match(p, s) is equivalent to re.search(r"^" + p, s) β but faster.π 2.2 re.search() β Find Anywhere
search() scans the string and returns the first match anywhere.
Step-by-step explanation:
- Step 1: Call
re.search(pattern, text). - Step 2: Returns the first match or
None. - Step 3: Use
.start()and.end()for positions.
import re text = "The year is 2026 and we are in June" m = re.search(r"\d+", text) if m: print("Found:", m.group()) print("Start:", m.start()) print("End: ", m.end()) # Search for missing pattern m2 = re.search(r"\d{5}", text) print("\n5 digits:", m2) # Multiple candidates β search returns the FIRST m3 = re.search(r"\w+", "first second third") print("\nFirst word:", m3.group())
π 2.3 fullmatch() β Match the Entire String
fullmatch() requires the pattern to match the entire string.
Step-by-step explanation:
- Step 1: Use
fullmatch()for validation. - Step 2: Returns a match only if the pattern covers the whole string.
- Step 3: Ideal for validating formats like phone numbers.
import re # Validate a 3-letter code print(re.fullmatch(r"[A-Z]{3}", "ABC")) print(re.fullmatch(r"[A-Z]{3}", "ABCD")) # None β too long # Validate a phone number phone = "555-1234" m = re.fullmatch(r"\d{3}-\d{4}", phone) print("\nPhone valid:", bool(m)) # Wrong format bad = "555-12345" print("Bad valid: ", bool(re.fullmatch(r"\d{3}-\d{4}", bad)))
fullmatch() for form validation β it's the cleanest way to enforce a complete format.π 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.
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)
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
Matchobjects. - Step 3: Access
.group(),.start(),.end().
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,\2to reference captured groups. - Step 3: Limit replacements with
count=n.
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))
π 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.
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.
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().
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())
π 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().
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.
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")
π 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.
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
\1to require the same word again. - Step 3: Find repeated words with
r"\b(\w+)\s+\1\b".
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)
π© 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.Ias a flag. - Step 2: Both "Hello" and "HELLO" match "hello".
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.
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.Slets.cross newlines. - Step 2:
re.Xignores whitespace and#comments in patterns. - Step 3: Combine flags with
|.
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.
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)
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.
"Regex is a language of its own β once you speak it, text becomes queryable." β Glenn Junsay Pansensoy (@PoeticGlenn)