Regular Expressions
import re
re.findall(r"\d+", "Room 12, floor 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
| Pattern | Matches |
|---|---|
\d | any digit 0–9 |
\w | a letter, digit or underscore |
\s | whitespace (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
| Quantifier | Meaning |
|---|---|
+ | 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
| Function | Does |
|---|---|
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,subcover most jobs.
See it in actionPulling numbers out of text
findall returns every match; a group captures just part of a match.
Try it yourselfExample 1: Find all numbers
\d+ means one or more digits in a row.
Output appears hereFind the numbers
Fill the blanks so the program finds every number in the text: ['3', '12', '7'].
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.
Output appears hereToo 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.
Spot the emails
Print every email address in the text as a list: ['mim@school.edu', 'joy@mail.com'].
Example 3: Groups capture parts
Named groups make the code self-explaining.
Output appears herePull out the parts
Fill the blanks so the program takes the day and month from 06/11 and prints day 06 month 11.
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.
Output appears hereSquash the spaces
Replace every run of spaces with a single space using re.sub. "too many spaces" becomes too many spaces.
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.
Example 5: Parsing log lines with VERBOSE and MULTILINE
Comments inside the pattern explain each part.
Output appears here3Level 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.
Output appears hereExample 7: Replacing with a function
Phone numbers are masked; temperatures are converted inside the text.
Output appears herere.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.What does this print?
import re print(re.findall(r"\d+", "a1b22c333"))
50 graded problems are waiting in Topic Practice.