Reading history

Python Regex: re.search, findall, sub and Groups

4 min read 1 views

Learn Python regular expressions with the re module: search, match, findall, sub, split, a regex cheat sheet, groups and named groups.

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, match and findall
  • 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

PatternMatches
\d / \DA digit / a non-digit
\w / \WA word character (letter, digit, _) / anything else
\sWhitespace
.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|bEither 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

  1. Calling .group() on None. When nothing matches, search() returns None; check it first.
  2. Using match() when you meant search().
  3. Forgetting to escape special characters. A literal dot is \., a literal plus is \+.
  4. 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

  • search finds the first match, findall finds all, match checks the start.
  • sub replaces and split splits by a pattern.
  • Write patterns as raw strings: r"\d+".
  • Groups (...) extract parts of a match.
Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *