Python RegEx · Exercises
Practical Python

Python RegEx Exercises

4 exercises that build on the Python Regular Expressions (regex) lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: A regular expression (regex) is a short pattern that describes the shape of some text — such as "three digits, a dash, then four digits" — which Python's re module uses to find, extract, check and replace text. By the end you can write simple patterns with \d, \w, \s and quantifiers, use re.search, re.findall, re.fullmatch and re.sub, pull parts out of a match with groups, and recognise when plain string methods are the better tool. You will practise: Extract every number; Predict the matches; Fix the year extractor; Validate and tidy phone numbers.

0 / 4 completed

Python RegEx practice exercises

1. Extract every number

Write code Easy

Write extract_numbers(text) that returns a list of ints, one for every whole number in text, in order. Return an empty list if there are none.

Your code
import re

def extract_numbers(text):
    # find every run of digits and return them as ints
    pass

print(extract_numbers("I bought 3 apples for 120 rupees"))

2. Predict the matches

Predict the output Medium

Read each pattern carefully and type exactly what the program prints.

Read this code
import re

text = "cat cart scat car"
print(re.findall(r"ca.", text))
print(re.findall(r"\bca\w*", text))
print(re.sub(r"a", "o", "banana", count=2))

3. Fix the year extractor

Fix the bug Medium

get_year(text) should return the year of the first date (written YYYY-MM-DD) as an int, or None if there is no date. It crashes with IndexError: no such group. Fix the pattern.

Your code
import re

def get_year(text):
    m = re.search(r"\d{4}-\d{2}-\d{2}", text)
    if m:
        return int(m.group(1))
    return None

print(get_year("Invoice dated 2023-11-02"))
print(get_year("No date here"))

4. Validate and tidy phone numbers

Write code Hard

Write normalize_phone(text) for 7-digit phone numbers. It should accept any of these styles — 555-0142, 555 0142, 5550142, (555) 0142, (555)0142 — with optional spaces around the whole thing, and return the standard form "555-0142". For anything else (wrong number of digits, extra text, letters) return None.

Your code
import re

def normalize_phone(text):
    # use re.fullmatch with two groups: 3 digits and 4 digits
    pass

for raw in ["555-0142", "(555) 0199", "5550123", "55-501"]:
    print(raw, "->", normalize_phone(raw))

Next lessonPython requests: Call Web APIs

More Python Regular Expressions (regex) examples · All Python exercises