Python · Module 08: Intermediate & Modern PythonTutorial 25 of 30
All Tutorials·~1.5 hrs

8.4 Regular Expressions (re Module) Explained Visually

Stop fearing regex! Learn Python's re module visually: essential pattern tokens, why you always use raw strings r'', capture groups, and real-world log/email/date extraction.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. What Is Regex? (The Super-Powered Ctrl+F Analogy)

Normal Ctrl+F only finds exact text like "2026-11-20". A Regular Expression (Regex) lets you search for a pattern — like "find ANY 4-digit year, hyphen, 2-digit month, hyphen, 2-digit day anywhere in a 10,000-line log file!"

Visual: Regex Capture Groups Extracting Date Parts from `"2026-11-20"`
r"(\d{4})-(\d{2})-(\d{2})"group(1) · Year"2026"group(2) · Month"11"group(3) · Day"20"

Golden Rule in Python: Always prefix regex patterns with r"" (raw string) so Python doesn't treat \d or \n as string escapes!


2. The 10 Regex Tokens That Cover 95% of Real Work

TokenMatchesExample
\dAny digit (0–9)\d{4} → "2026"
\wWord character (letter, digit, _)\w+ → "user_42"
\sWhitespace (space, tab, newline)\s+ → " "
.Any character (except newline)a.c → "abc", "a9c"
+1 or more of previous token\d+ → "12345"
*0 or more of previous tokena* → "", "aaa"
?0 or 1 (optional)https? → "http" or "https"
{n,m}Between n and m repetitions\d{2,4}
^ / $Start / End of string^\d+$ → digits only!
( ... )Capture Group (extract sub-match)(\d{4})-(\d{2})

3. The 4 re Functions You Actually Need

PYTHON
import re

log = "2026-11-20 ERROR user=riya@example.com code=503"

# 1) re.search() — Finds FIRST match anywhere in the string!
m = re.search(r"(\d{4})-(\d{2})-(\d{2})", log)
if m:
    print(m.group(0))               # 2026-11-20 (full match)
    print(m.groups())               # ('2026', '11', '20')

# 2) re.findall() — Returns a list of ALL matches
nums = re.findall(r"\d+", "Order #42: 3 items for $199")
print(nums)                         # ['42', '3', '199']

# 3) re.sub() — Search & Replace (great for redacting PII!)
masked = re.sub(r"\d", "*", "Card 4111-2222")
print(masked)                       # Card ****-****

Beginner Trap (re.match vs. re.search): re.match() ONLY checks the very start of the string! Almost always use re.search() unless you intentionally want a start-only match.


4. Interactive Trace: Extracting Fields from a Log Line

Tracing re.search() with Capture Groups
Interactive Line-by-Line Execution Trace · Step 1 of 4
1import re
2→line = "Order #9041 by Aarav ($49.50)"
3m = re.search(r"#(d+) by (w+)", line)
4order_id, buyer = m.groups()
5print(f"{buyer} -> {order_id}")
Variables in Memory
line"Order #9041 by Aarav ($49.50)"str
Console Output
(nothing printed yet)
What just happened: Raw unstructured text line containing an order ID and buyer name.

Quick Quiz: Module 8.4 — Regular Expressions

Q1.What is the key difference between `re.match()` and `re.search()`?
Q2.What does `re.findall(r"\d+", "a12b345c6")` return?
Q3.Why should Python regex patterns always use raw strings `r"..."`?

Keep Exploring: Related Lessons & Tools

All Courses →