Skip to content

Module 15 · Python Standard Libraries — topic 13 of 13

re

Regular expressions with re: search, match, fullmatch, findall and finditer, substitution with sub, splitting, groups and named groups, character classes and quantifiers, flags and compiled patterns.

Beginner 12 min read·Lesson 234 of 306 in Python Programming

Learning objectives

  • Write basic patterns with classes and quantifiers
  • Search, extract and replace text
  • Use groups, named groups, flags and compiled patterns

Definition

The re module provides regular expressions: patterns that describe sets of strings. They are used to search text, validate formats, extract parts and replace text.

Introduction

Find every order number in a log, check that a vehicle registration looks valid, reformat dates — regular expressions do these in a line or two.

Why it matters

Text processing is everywhere, and regular expressions are the standard tool across languages, editors and command-line utilities.

Detailed explanation

Write patterns as raw strings (r"\d+") so backslashes reach the regex engine unchanged.

Building blocks: \d digit, \w word character, \s whitespace, . any character, [abc] a set, [^abc] not in set, ^ start, $ end.

Quantifiers: * zero or more, + one or more, ? optional, {n} exactly n, {m,n} between m and n. Add ? (*?, +?) for non-greedy matching.

re.search finds the first match anywhere; re.match only at the start; re.fullmatch requires the whole string to match.

re.findall returns all matches (or group contents); re.finditer yields match objects; re.sub replaces matches (\1 refers to groups); re.split splits on a pattern.

Parentheses create groups, read with m.group(1) or m.groups(); (?P<name>...) creates named groups read with m["name"].

Flags change behaviour: re.IGNORECASE, re.MULTILINE, re.VERBOSE. re.compile(pattern) prepares a pattern for repeated use.

Syntax

Python
import re
re.search(r"\d+", "Order 1042")
re.findall(r"#(\d+)", text)
re.sub(r"\s+", " ", text)
pattern = re.compile(r"(?P<year>\d{4})-(?P<month>\d{2})")
  • Use raw strings.
  • search, findall, sub, split.
  • Groups extract parts.

Code examples

Finding and extracting

Python
import re
text = "Order #1042 shipped on 2026-11-27; order #1043 pending."
print(re.findall(r"#(\d+)", text))
m = re.search(r"(\d{4})-(\d{2})-(\d{2})", text)
print(m.group(0), m.groups())
Output
['1042', '1043']
2026-11-27 ('2026', '11', '27')

Replacing, splitting and validating

Python
import re
print(re.sub(r"\s+", " ", "too many spaces"))
print(re.split(r"[,;]\s*", "a, b;c ,d"))
print(re.fullmatch(r"[A-Z]{2}\d{2}", "KA05") is not None)
Output
too many spaces
['a', 'b', 'c ', 'd']
True

More examples

Parsing logs and validating emails

Python
import re
LOG = re.compile(r"(?P<time>\d{2}:\d{2}) (?P<level>INFO|WARN|ERROR) (?P<msg>.+)")
lines = ["09:00 INFO server started", "09:05 WARN slow query", "garbage line", "09:10 ERROR disk full"]
for line in lines:
m = LOG.match(line)
if m:
print(m["level"], "@", m["time"], "-", m["msg"])
else:
print("unparsed:", line)
EMAIL = re.compile(r"^[\w.+-]+@[\w-]+(\.[\w-]+)+$")
print([e for e in ["asha@example.com", "bad@", "ravi.k+news@mail.co.in"] if EMAIL.match(e)])
print(re.sub(r"(\d{4})-(\d{2})-(\d{2})", r"\3/\2/\1", "due 2026-12-01"))
Output
INFO @ 09:00 - server started
WARN @ 09:05 - slow query
unparsed: garbage line
ERROR @ 09:10 - disk full
['asha@example.com', 'ravi.k+news@mail.co.in']
due 01/12/2026

Step-by-step explanation

  • Named groups make the log fields self-describing: m["level"] instead of m.group(2).
  • The email pattern is a practical check, not a complete validator of every legal address.
  • In the replacement, \3/\2/\1 reorders the captured year, month and day.

Expected output

Running “Parsing logs and validating emails” prints exactly:

TextOutput
INFO @ 09:00 - server started
WARN @ 09:05 - slow query
unparsed: garbage line
ERROR @ 09:10 - disk full
['asha@example.com', 'ravi.k+news@mail.co.in']
due 01/12/2026

Practical applications

  • Extracting IDs, dates and amounts from logs and documents.
  • Form validation for phone numbers and postcodes.

Best practices

  • Use raw strings and compile patterns you reuse.
  • Prefer named groups for readability.
  • Use string methods when a regex isn't needed.

Common mistakes

Forgetting raw strings

Avoid

re.search("\bword\b", text) # \b becomes a backspace

Prefer

re.search(r"\bword\b", text)

Without r, Python interprets escape sequences before re sees them.

match instead of search

Avoid

re.match(r"\d+", "Order 42") # None

Prefer

re.search(r"\d+", "Order 42")

match only checks the beginning of the string.

Important notes

  • This completes the standard library module; next come external libraries and web APIs.

Key takeaways

  • Patterns combine classes, quantifiers and anchors.
  • search/findall/sub/split cover most tasks.
  • Groups extract parts; flags and compile refine use.

Try it yourself

  1. 1
    Extract all Indian mobile numbers (10 digits starting with 6–9) from a paragraph.
  2. 2
    Convert dates from DD/MM/YYYY to YYYY-MM-DD in a text using re.sub.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

2 questions test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this topic