Skip to contentSkip to navigation

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

    \d is a digit, \w a letter or digit, \s a space, . any character.

  • Repetition

    + means one or more, * zero or more, ? optional, {3} exactly three.

  • Three finders

    search finds the first match, fullmatch checks the whole text, findall lists 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.

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.

Python
import re
text = "Tickets: 3 adults, 12 children, 1 dog"
print(re.findall(r"\d+", text))
print(re.findall(r"[a-z]+", text))
Output
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.

  1. import re
  2. log = "ERROR 404 at 10:15, ERROR 500 at 11:02"
  3. codes = re.findall(r"ERROR (\d+)", log)
  4. first = re.search(r"\d\d:\d\d", log)
  5. clean = re.sub(r"\d", "*", log[:9])
  6. print(codes)
  7. print(first.group())
  8. 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 notesOpen

A pattern language

A regular expression (regex) is a small pattern that describes a set of strings. Python's re module searches text for them:

Try it 1: edit me, then Run
import re

match = re.search(r"\d+", "Order 66 shipped")
print(match.group())      # 66
Output
Press Run to see what it prints.

\d means "any digit" and + means "one or more of the previous thing", so \d+ matches a run of digits. re.search scans the text and returns a match object for the first place the pattern fits, or None if it fits nowhere. match.group() is the text that matched.

Always use raw strings

Patterns are full of backslashes. In a normal string, Python itself treats some backslash sequences specially, such as "\n" for a newline and "\b" for a backspace character. Writing patterns as raw strings, with an r before the quote, tells Python to leave every backslash alone so the re module sees exactly what you typed: r"\bcat\b". Make it a habit for every pattern.

The building blocks

Pattern Matches
abc the exact text abc
. any one character except a newline
\d a digit; \D is anything that is not a digit
\w a "word" character: letter, digit or underscore
\s whitespace: space, tab or newline
[aeiou] any one of the listed characters
[a-z], [0-9A-F] any one character in the ranges
[^0-9] any one character not listed
\b a word boundary (start or end of a word)

To match a character that has a special meaning, such as a dot or a plus sign, put a backslash in front of it: \. matches a real full stop.

Repetition

These go after the thing they repeat:

Pattern Meaning
* zero or more
+ one or more
? zero or one (optional)
{3} exactly three
{2,4} between two and four

So colou?r matches both spellings, and \d{3}-\d{4} matches 555-0199. Repetition is greedy: it matches as much as it can while the rest of the pattern still fits.

search, fullmatch and findall

The three functions answer different questions:

Try it 2: edit me, then Run
text = "Call 555-0199 or 555-0123"
print(re.search(r"\d{3}-\d{4}", text).group())    # 555-0199  (first match)
print(re.findall(r"\d{3}-\d{4}", text))           # ['555-0199', '555-0123']
print(re.fullmatch(r"\d{3}-\d{4}", "555-0199"))   # a match: the WHOLE string fits
print(re.fullmatch(r"\d{3}-\d{4}", "x555-0199"))  # None
Output
Press Run to see what it prints.

Use search to find something anywhere, findall to collect every match as a list of strings, and fullmatch to validate: it only succeeds if the entire string fits the pattern. A common mistake is validating with search, which happily finds a valid-looking piece inside invalid text. Because a match object is truthy and None is falsy, you can write if re.fullmatch(pattern, text):.

Anchors

^ matches the start of the text and $ the end. re.search(r"^\d+$", text) behaves like fullmatch. Anchors are also useful on their own: r"^#" finds lines that start with a hash.

Groups

Round brackets make a group, which captures part of the match separately:

Try it 3: edit me, then Run
m = re.search(r"(\d{2})/(\d{2})/(\d{4})", "Due 03/11/2024")
print(m.group(0))     # 03/11/2024   (the whole match)
print(m.group(1))     # 03
print(m.groups())     # ('03', '11', '2024')
Output
Press Run to see what it prints.

With groups, findall returns tuples of the groups instead of whole matches:

Try it 4: edit me, then Run
pairs = re.findall(r"(\w+)=(\d+)", "a=1, b=22, c=333")
print(pairs)          # [('a', '1'), ('b', '22'), ('c', '333')]
Output
Press Run to see what it prints.

Brackets also group for repetition: (ha)+ matches hahaha. And | means "or": cat|dog matches either word.

Replacing and splitting

re.sub(pattern, replacement, text) replaces every match. re.split(pattern, text) splits wherever the pattern matches:

Try it 5: edit me, then Run
print(re.sub(r"\s+", " ", "too    many   spaces"))   # too many spaces
print(re.sub(r"\d", "#", "PIN 4821"))                 # PIN ####
print(re.split(r"[,;]\s*", "a, b;c ,d"))              # ['a', 'b', 'c ', 'd']
Output
Press Run to see what it prints.

Flags

Optional flags change how matching works. re.IGNORECASE makes letters match either case: re.search(r"error", "ERROR: disk", re.IGNORECASE) finds a match.

When not to use a regex

Regular expressions are powerful but dense, and a long one is hard to read and easy to get subtly wrong. If a string method does the job, use it: text.startswith("http"), "@" in email, line.split(","). Reach for re when you need classes, repetition or groups. Keep each pattern short, test it on a few good and bad examples, and add a comment saying what it is meant to match.

Syntax

The general shape of the statements in this lesson.

syntax.py
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, or
Output
Press 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

Beginner

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.

Python
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)
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

-? makes the minus sign optional, \d+\.\d{2} needs digits, a real dot and exactly two decimals, so the quantity 2 in "2 x 0.95" is not mistaken for a price. The total line is left out before summing. findall returns strings, so each one is converted with float.

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.

Buggy code: run it
import re
print(re.findall("\bcat\b", "cat scat cat"))
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints [] because \b in a normal string is a backspace character, not a word boundary

Write this instead

import re
print(re.findall(r"\bcat\b", "cat scat cat"))

Why it happens

Python turns some backslash sequences into special characters before re ever sees the pattern.

In the real world

Where this shows up in software people use every day.

  1. Summarising a web server log

    Web operations

    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.

    Python
    import 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)
    Output
    Press 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?

Repetition is greedy. In <.+> applied to <a><b>, the match is the whole string. Add ? after the repetition, as in <.+?>, to match as little as possible.

Should I use a regex to validate email addresses?

Only a simple one, such as checking for something, an @ and a dot after it. Fully correct email patterns are enormous. The real test is sending a confirmation email.

How do I test a pattern quickly?

Try it on a short list of strings that should match and a list that should not, and print the results side by side, as the worked examples do. Testing the bad cases matters most, because a pattern that matches too much often looks fine on good data.

Is there a way to name groups?

Yes: (?P<year>\d{4}) creates a group you read with m.group('year'). Named groups make longer patterns much easier to read.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

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.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

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.