Regular Expressions
- Match patterns with
re.search,re.match,re.findall - Use character classes, quantifiers, and anchors
- Capture groups to extract substrings
- Substitute matched text with
re.sub
re powers log parsing, Django URL routing, and every scraper. Catastrophic backtracking in nested quantifiers has taken down real services (Cloudflare 2019). Knowing re.compile, named groups, and re.VERBOSE separates hobbyists from engineers.
- Recompiling the same pattern in a loop — hoist to module scope with
re.compile()for a real speedup. - Using greedy
.*when you want.*?— you'll match across delimiters and get one giant blob. - Parsing HTML or emails with regex — reach for
BeautifulSouporemail.parserbefore you regret it.
A pattern language for text. Python's re module:
Three workhorses
re.findall(pattern, text)— every non-overlapping match, as a listre.search(pattern, text)— first match anywhere, orNonere.sub(pattern, repl, text)— replace matches
Cheat sheet
\ddigit ·\wword char ·\swhitespace+one or more ·*zero or more ·?optional( )capture group ·[abc]any of a/b/c
Use raw strings
Always prefix patterns with r to avoid backslash hell: r"\d+".
Try it
- Extract all numbers from
"order #1234, total ₹5,600". - Replace double-spaces with single in
"a b c".
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
- Exercise 1
From
text = "order #A12 and #B34567 arrived — see #C9", usere.findallto extract every#-prefixed code (letter + digits). Print the list. Expected:['A12', 'B34567', 'C9'](without the#). - Exercise 2
Use
re.subto redact every 10-digit phone number intext = "Call 9876543210 or 9123456789 today"— replace each withXXX-XXX-XXXX— then print. Expected output includesCall XXX-XXX-XXXX or XXX-XXX-XXXX today. - Exercise 3
From
log = "user alice@x.com and bob.smith@company.io signed in", extract all email addresses usingre.findalland print the list. Expected:['alice@x.com', 'bob.smith@company.io'].