Module 11 · Lesson 01
Regular Expressions
Find and check patterns in text with the re module: character classes, repetition and anchors, search versus fullmatch, findall, groups and sub, always written as raw strings.
- About 8 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Building blocks of a pattern
- search, fullmatch and findall
- Groups and replacing
- Watch codes come out of a log
Patterns that find text
A regular expression describes the shape of the text you want, such as "three digits" or "a word, then an @".
Raw strings
Write patterns as
r"..."so Python leaves the backslashes alone.Building blocks
\dis a digit,\wa letter or digit,\sa space,.any character.Repetition
+means one or more,*zero or more,?optional,{3}exactly three.Three finders
searchfinds the first match,fullmatchchecks the whole text,findalllists every match.
Patterns everywhere
Whenever a program hunts for text with a certain shape, a pattern is probably doing it.
- Search toolsFind every phone number or date in a long page of text.
- Log filesPull the time and error code out of each line of a log.
- Sign-up formsCheck that a postcode or a username has the right shape.
- Text editorsFind and replace with a pattern, not just an exact word.
Searching for a time
This line looks for a time like 07:30 in some text. Tap each part to see its job.
Part 1 of 4
module:The regular expression module, loaded with import re.
Find text by its shape
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6findall
findall returns every piece of text that fits the pattern, as a list.
Your turn: Change the second pattern to [A-Z][a-z]+ to find only words that start with a capital.
import re text = "Tickets: 3 adults, 12 children, 1 dog" print(re.findall(r"\d+", text)) print(re.findall(r"[a-z]+", text))
Press Run to see what it prints.Watch codes come out of a log
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- import re
- log = "ERROR 404 at 10:15, ERROR 500 at 11:02"
- codes = re.findall(r"ERROR (\d+)", log)
- first = re.search(r"\d\d:\d\d", log)
- clean = re.sub(r"\d", "*", log[:9])
- print(codes)
- print(first.group())
- print(clean)
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.Every vowel in a word:
import re
print(re.findall(r"[aeiou]", "banana"))0 of 6 answered
Common regex misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
import re
re.search(r"\d+", text) # first match or None
re.fullmatch(r"[A-Z]\d{3}", s) # whole string must fit
re.findall(r"\w+", text) # list of all matches
m.group(), m.group(1), m.groups()
re.sub(r"\s+", " ", text) # replace every match
re.split(r"[,;]", text) # split on a pattern
\d \w \s . [abc] [^abc] [a-z] # classes
* + ? {n} {m,n} # repetition
^ $ \b ( ) | # anchors, groups, orPress Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
Pulling prices out of a receipt
A receipt is stored as plain text. Find every price written as digits, a dot and two digits, add them up, and find the line with the largest price.
import re
receipt = """Bread 1.85
Coffee beans 7.40
Milk 2 x 0.95
Discount -1.00
Total due 10.15"""
lines = receipt.splitlines()[:-1]
prices = []
for line in lines:
for amount in re.findall(r"-?\d+\.\d{2}", line):
prices.append(float(amount))
print(prices)
print("Sum:", round(sum(prices), 2))
biggest = max(lines, key=lambda line: float(re.findall(r"-?\d+\.\d{2}", line)[-1]))
print("Largest line:", biggest)Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Forgetting the raw string
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
import re
print(re.findall("\bcat\b", "cat scat cat"))Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Web operations
Summarising a web server log
An operations team wants to know which pages fail most often. Each log line holds an address, a method, a path and a status code, and a regex pulls out the parts they need.
Why Python fits
Four groups capture the address, method, path and status in one step, and
groups()unpacks them into named variables.\S+means one or more non-space characters, which suits a path. Lines that do not fit are counted instead of crashing the report.Pythonimport re log = """10.0.0.4 GET /home 200 10.0.0.9 GET /cart 500 10.0.0.4 POST /login 401 10.0.0.7 GET /cart 500 10.0.0.9 GET /home 200 bad line here""" pattern = r"^(\d+\.\d+\.\d+\.\d+) (GET|POST) (\S+) (\d{3})$" failures = {} skipped = 0 for line in log.splitlines(): m = re.fullmatch(pattern, line) if not m: skipped += 1 continue ip, method, path, status = m.groups() if status.startswith("5"): failures[path] = failures.get(path, 0) + 1 print("Server errors:", failures) print("Unreadable lines:", skipped)OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Why does my pattern match too much?
Should I use a regex to validate email addresses?
How do I test a pattern quickly?
Is there a way to name groups?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 10 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.