Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Regular Expressions

18 min 40 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 4 of 5 · View course roadmap
Step 1

Learn the idea

Regex is a mini-language for pattern matching — intimidating at first, unstoppable once learned. Core vocabulary:

  • \d digit, \w word char, \s whitespace, . 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 — always r"...".
  • 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.

Step 2

Try it yourself

Blank · autosaved

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”.

PYexample.py
+ Enter to run
Output appears here…
Step 3

Pass the challenge +40 XP

Blank · autosaved

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.

Target output
ada@lovelace.io
grace@navy.mil
PYchallenge.py
Run your code to check it…
Step 4

Check your understanding

1. What does \d+ match?
2. Why write regex as r"..." raw strings?
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path