Regular Expressions
Lesson 4 of 5 · View course roadmap
Learn the idea
Regex is a mini-language for pattern matching — intimidating at first, unstoppable once learned. Core vocabulary:
\ddigit,\wword char,\swhitespace,.any char+one-or-more,*zero-or-more,?optional,{3}exactly 3[abc]character set,^start,$end(...)capture group — extract just that part
Python API: re.search(pat, s) (first match or None), re.findall(pat, s) (all matches as a list), re.sub(pat, repl, s) (replace). Always write patterns as raw strings: r"\d+".
Where you'll use this
Log mining, input validation, scraping, bulk find-and-replace across a codebase, extracting order IDs from emails — regex is the universal text power tool, identical in Python, JavaScript, grep and your editor's search box.
Common mistakes
- Forgetting the raw string:
"\d"may work by luck but"\b"silently becomes backspace — alwaysr"...". - Greedy matching surprises:
<.*>eats from the first < to the LAST >. The non-greedy version is<.*?>. - re.match only checks the start of the string — you almost always want re.search or re.findall.
- Validating emails 'perfectly' with regex — a pragmatic pattern plus a confirmation email is the professional answer.
Pro tip
Build every non-trivial pattern interactively on regex101.com (set flavor to Python) — it explains each token live and saves you from blind trial and error. Bookmark it; professionals use it weekly.
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +40 XP
Use re.findall to extract all email addresses from the starter text and print each on its own line. Pattern hint: word chars + @ + word chars + . + word chars.
ada@lovelace.io grace@navy.mil
r"\w+@\w+\.\w+" is enough for this text.
import re
text = "Contact ada@lovelace.io or grace@navy.mil for details; spam@@bad is not valid."
for email in re.findall(r"\w+@\w+\.\w+", text):
print(email)
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.