Focused practice · 9 min read

Python Regex Exercises: Search, Find, and Replace

Regular expressions are a compact language for text patterns. Start with one clear pattern, test it on a small string, and only then add groups or quantifiers.

Use raw strings

Write regex patterns as raw strings, such as r"\d+". The r prefix stops Python from interpreting backslashes before the regex engine sees them. This avoids a common source of confusing bugs.

import re
print(re.findall(r"\d+", "a1 b22 c333"))

Digits with a raw string

Search for one match

re.search returns a match object for the first occurrence, or None. Read the text with group(). Check for None before using the result, especially when the input comes from a user or a file.

import re
match = re.search(r"\d+", "Order 42")
if match:
    print(match.group())

Check before reading

Find all matches

re.findall returns a list of every non-overlapping match. Character classes let one pattern match a set of characters: [A-Z] finds uppercase letters. Combine classes with quantifiers to describe repetition.

import re
print(re.findall(r"[A-Z]", "pyTHON"))
print(re.findall(r"\d+", "a1 b22"))

Collect every match

Replace text

re.sub replaces every match with a replacement string. A pattern such as \s+ matches runs of whitespace. Test the replacement on a small sample before applying it to a whole document.

import re
text = "latte   tea  mocha"
print(re.sub(r"\s+", " ", text))

Normalise spacing

Validate a simple shape

re.fullmatch checks that the whole string matches the pattern. Here \d{3}-\d{4} describes three digits, a hyphen, and four digits. Return a boolean when the caller only needs to know whether the input is valid.

import re
phone = "555-1234"
print(bool(re.fullmatch(r"\d{3}-\d{4}", phone)))

A whole-string check

Your practice checklist

Common questions

Why use r"..." for regex patterns?

The raw string keeps backslashes literal, so the regex engine receives the pattern you intended.

What is the difference between search and findall?

search returns the first match object or None. findall returns a list of all matching strings.

When should I avoid regex?

When a simple string method such as split, replace, or startswith expresses the rule clearly. Regex is best for genuinely pattern-based text.

Practice regular expressions

12 questions on search, findall, sub, character classes, and raw strings.

Open practice

Keep reading: