A regular expression (regex) is a small pattern language for finding text: “five digits, a dash, six digits” or “something that looks like an email address”. Python’s built-in re module uses these patterns to search, extract, replace and split text. This lesson covers the main functions, the most useful symbols, and capturing groups.
In this lesson you will learn
- The difference between
search,matchandfindall - How to replace and split text with patterns
- The most common regex symbols
- How to extract parts with groups and named groups
- Why patterns are written as raw strings
Searching, Finding, Replacing and Splitting
import re
text = "Call 01711-223344 or 01922-556677 before 5 pm."
print(re.search(r"\d{5}-\d{6}", text).group())
print(re.findall(r"\d{5}-\d{6}", text))
print(re.sub(r"\d{6}", "******", text))
print(bool(re.match(r"Call", text)), bool(re.match(r"before", text)))
print(re.split(r"\s+or\s+", "tea or coffee or juice"))
Output
01711-223344
['01711-223344', '01922-556677']
Call 01711-****** or 01922-****** before 5 pm.
True False
['tea', 'coffee', 'juice']
re.search()finds the first match anywhere and returns a match object;.group()gives the matched text.re.findall()returns every match as a list.re.sub(pattern, new, text)replaces each match, which is handy for hiding phone or card numbers.re.match()only checks the start of the string, so “before” is not found even though it appears later.re.split()splits wherever the pattern matches.
Always use raw strings: r”…”
In a normal string, \d and \b may be treated as escape characters. The r prefix passes backslashes to the regex engine unchanged.
Regex Cheat Sheet
| Pattern | Matches |
|---|---|
\d / \D | A digit / a non-digit |
\w / \W | A word character (letter, digit, _) / anything else |
\s | Whitespace |
. | Any character except newline |
^ / $ | Start / end of the string |
*, +, ? | 0 or more, 1 or more, 0 or 1 |
{n}, {m,n} | Exactly n, between m and n |
[abc], [a-z] | One of the listed characters |
(...) | A capturing group |
a|b | Either a or b |
Validating and Extracting with Groups
import re
pattern = re.compile(r"^[\w.+-]+@[\w-]+\.[\w.]+$")
for email in ["rafi@example.com", "nila.k@mail.co.uk", "bad@", "no-at-sign.com"]:
print(f"{email:<20} {'valid' if pattern.match(email) else 'invalid'}")
date = "Exam on 2026-12-16"
m = re.search(r"(\d{4})-(\d{2})-(\d{2})", date)
year, month, day = m.groups()
print(day, month, year)
m = re.search(r"(?P<user>\w+)@(?P<site>[\w.]+)", "mail rafi@example.com now")
print(m.group("user"), m.group("site"))
Output
rafi@example.com valid
nila.k@mail.co.uk valid
bad@ invalid
no-at-sign.com invalid
16 12 2026
rafi example.com
re.compile()prepares a pattern once for repeated use.^and$anchor the email pattern so the whole string must match. It is a simple check for well-formed input, not a full email validator.- Brackets create groups;
.groups()returns them as a tuple to unpack. (?P<name>...)creates a named group, read with.group("name").
Common Mistakes
- Calling
.group()onNone. When nothing matches,search()returnsNone; check it first. - Using
match()when you meantsearch(). - Forgetting to escape special characters. A literal dot is
\., a literal plus is\+. - Greedy matching.
<.*>grabs as much as possible; use<.*?>for the shortest match.
Practice Exercises
Exercise 1. Extract all whole numbers from "3 apples, 12 mangoes and 7 bananas".
Show answer
import re
print(re.findall(r"\d+", "3 apples, 12 mangoes and 7 bananas")) # ['3', '12', '7']
Exercise 2. Replace runs of spaces with a single space.
Show answer
print(re.sub(r" +", " ", "too many spaces"))
Frequently Asked Questions
How do I make a regex case-insensitive?
Pass the flag re.IGNORECASE (or re.I), for example re.search(r"python", text, re.I).
Should I use regex for everything?
No. For simple checks, string methods like startswith(), in and split() are clearer and faster. Use regex when the pattern is genuinely flexible.
Summary
searchfinds the first match,findallfinds all,matchchecks the start.subreplaces andsplitsplits by a pattern.- Write patterns as raw strings:
r"\d+". - Groups
(...)extract parts of a match.
