LearnPy Hub
AdvancedAdvancedLesson 23 of 32

Regular Expressions

Watch the ideaSearch text with a pattern
import re
re.findall(r"\d+", "Room 12, floor 3")
text
R
o
o
m
␣
1
2
,
␣
f
l
o
o
r
␣
3

A regular expression is a pattern. \d+ means “one or more digits in a row”.

1Level 1 · BasicsBasics

How would you find every phone number in a long message, or check that an email address looks valid? String methods like find() only search for fixed text. Regular expressions (regex) describe patterns of text, like "11 digits starting with 01". Python's re module uses them.

The building blocks

PatternMatches
\dany digit 0–9
\wa letter, digit or underscore
\swhitespace (space, tab, new line)
.any character except a new line
[aeiou]one character from the set; [a-z] is a range
^ / $start / end of the text

How many times? Quantifiers

QuantifierMeaning
+one or more
*zero or more
?optional (zero or one)
{3}, {2,4}exactly 3, between 2 and 4

So \d+ means "one or more digits" and 01\d{9} means "01 followed by exactly 9 digits".

Always use raw strings

Write patterns as r"\d+". The r stops Python from treating backslashes specially before the regex sees them.

The main functions

FunctionDoes
re.findall(p, text)list of all matches
re.search(p, text)first match anywhere, or None
re.fullmatch(p, text)does the whole text match? (validation)
re.sub(p, new, text)replace matches
re.split(p, text)split on a pattern

Groups: capturing parts

Round brackets capture part of a match. In r"(\d{4})-(\d{2})-(\d{2})", m.group(1) is the year. Named groups like (?P<year>\d{4}) are even clearer.

Key points: regex describes text patterns; \d \w \s . match kinds of characters; + * ? {n} say how many; use raw strings; findall, search, fullmatch, sub cover most jobs.

See it in actionPulling numbers out of text

findall returns every match; a group captures just part of a match.

Step-by-step

Try it yourselfExample 1: Find all numbers

\d+ means one or more digits in a row.

example_1.py
Output appears here
Fill in the blanks

Find the numbers

Fill the blanks so the program finds every number in the text: ['3', '12', '7'].

blanks.py
import re
print(re.(r"+", "3 cats, 12 dogs and 7 fish"))

Example 2: Validate a phone number

fullmatch checks the whole string. Try adding a letter or removing a digit.

example_2.py
Output appears here
Fix the bug

Too loose a check

A valid code is exactly 4 digits. This check says True for 12345, which is wrong. Fix the pattern so the output is True False.

buggy.py
Your turn

Spot the emails

Print every email address in the text as a list: ['mim@school.edu', 'joy@mail.com'].

my_code.py

Example 3: Groups capture parts

Named groups make the code self-explaining.

example_3.py
Output appears here
Fill in the blanks

Pull out the parts

Fill the blanks so the program takes the day and month from 06/11 and prints day 06 month 11.

blanks.py
import re
m = re.match(r"(\d+)/(\d+)", "06/11")
print("day", m.group(), "month", m.group())

Example 4: Clean text with sub and split

sub replaces every match; split breaks on any of several separators.

example_4.py
Output appears here
Your turn

Squash the spaces

Replace every run of spaces with a single space using re.sub. "too many spaces" becomes too many spaces.

my_code.py

2Level 2 · IntermediateNamed groups, flags and finditer

Named groups

(?P<year>\d{4}) captures a part with a name: m.group("year") or m.groupdict(). Much clearer than group numbers.

Flags

re.IGNORECASE ignores case, re.MULTILINE makes ^ and $ work on every line, and re.VERBOSE lets you spread a pattern over lines with comments.

finditer

re.finditer gives match objects one at a time, with positions (m.start(), m.end()). Use it for big texts or when you need where each match is.

Compile once

pattern = re.compile(r"...") lets you reuse a pattern many times.

See it in actionMatching step by step

Watch each match object and its named parts appear in the variables.

Step-by-step

Example 5: Parsing log lines with VERBOSE and MULTILINE

Comments inside the pattern explain each part.

example_5.py
Output appears here

3Level 3 · AdvancedLookarounds, greedy vs lazy, and function replacements

Greedy vs lazy

.* grabs as much as it can; .*? as little as it can. On <b>x</b><b>y</b>, <b>.*</b> matches everything, <b>.*?</b> just the first tag.

Lookahead and lookbehind

(?=...) and (?<=...) check what's around a position without including it. A password rule "at least one digit" is (?=.*\d). (?!...) means "not followed by".

Replacing with a function

re.sub(pattern, func, text) calls func(match) for every match and uses the return value, which is great for converting units or masking phone numbers.

Know when to stop

Regex is wrong for nested structures like HTML or JSON; use a real parser. Badly written patterns can also be very slow on long inputs.

Example 6: Greedy vs lazy and lookarounds

Each password is checked against four lookahead rules at once.

example_6.py
Output appears here

Example 7: Replacing with a function

Phone numbers are masked; temperatures are converted inside the text.

example_7.py
Output appears here
Common mistakere.match() only checks the start of the text, which surprises many people. Use re.search() to look anywhere and re.fullmatch() to validate the whole string.
Exercise · predict the output

What does this print?

import re
print(re.findall(r"\d+", "a1b22c333"))
Quick quiz · 5 questions
1. What does \d match?
2. What does the + quantifier mean?
3. Why write patterns like r"\d+"?
4. Which function checks that an entire string matches a pattern?
5. What does re.sub(r"a", "o", "banana") return?
Ready to practice regular expressions?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python Regular Expressions · LearnPy Hub