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.
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!"
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
| Token | Matches | Example |
|---|---|---|
\d | Any digit (0–9) | \d{4} → "2026" |
\w | Word character (letter, digit, _) | \w+ → "user_42" |
\s | Whitespace (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 token | a* → "", "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
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.matchvs.re.search):re.match()ONLY checks the very start of the string! Almost always usere.search()unless you intentionally want a start-only match.
4. Interactive Trace: Extracting Fields from a Log Line
Quick Quiz: Module 8.4 — Regular Expressions
Keep Exploring: Related Lessons & Tools
All Courses →Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.
Compute MD5, SHA-1, SHA-256, SHA-384, and SHA-512 hashes or keyed HMAC signatures directly in your browser using Web Crypto.