</>
Skip to content
Python lessons (33/45)

Python — RegEx

The re module

import re

pattern = r"\d{3}-\d{4}"          # raw string — backslashes stay literal

re.search(pattern, "Call 555-1234")     # Match or None
re.match(pattern, "555-1234")           # anchored at START only
re.findall(pattern, "555-1234, 555-5678")   # all matches as list
re.sub(pattern, "XXX", text)            # search & replace

Raw strings: always write patterns as r"..." so \d reaches the regex engine instead of Python interpreting the backslash.

Character building blocks

PatternMatches
\d / \w / \sdigit / word char / whitespace
.any character
[aeiou]one listed char; [a-z0-9] ranges
[^0-9]NOT a digit
^…$start / end anchors
colou?roptional (0–1)
\d{2,4}two to four
a+ / a*one+ / zero+

Groups extract pieces

Parentheses capture:

m = re.search(r"(\d{4})-(\d{2})-(\d{2})", "Released 2026-08-23")

m.group(0)    # "2026-08-23"  whole match
m.group(1)    # "2026"
m.group(2, 3) # ("08", "23")

# named groups — self-documenting:
m = re.search(r"(?P<year>\d{4})-(?P<month>\d{2})", "2026-08")
m["year"]     # "2026"

split & sub with patterns

re.split(r"[;,]", "a,b;c")        # ['a', 'b', 'c']
re.sub(r"\s+", " ", "too   many   spaces")
re.sub(r"(\w+)@(\w+)", r"<\1 at \2>", "ada@py")   # groups reused in replacement

Practical pattern collection

email_ok = re.fullmatch(r"\S+@\S+\.\S+", email)
phone = re.search(r"\b\d{10}\b", text)
words = re.findall(r"\b\w+\b", sentence)         # tokenizer
slug = re.sub(r"[^\w]+", "-", title.lower()).strip("-")

Flags

re.search(r"hello", text, re.IGNORECASE)   # case-insensitive
re.findall(r"^.", text, re.MULTILINE)      # ^ per line
re.search(r"a  b", text, re.VERBOSE)       # ignore spaces in pattern + comments

match vs search vs fullmatch

FunctionSucceeds when pattern matches…
matchstarts at position 0
searchanywhere in string
fullmatchthe ENTIRE string

Validation wants fullmatch; extraction wants search/findall.

Honest limits

Regex can't parse nested HTML/JSON reliably, and mega-patterns become write-only. Use it for shapes; use real parsers for structured data.

Mini Practice

  1. Extract every word ≥5 letters from a paragraph.
  2. Validate five phone shapes with fullmatch.
  3. Named-group parse "name=Alice;age=36".
  4. Slugify three titles via sub.
  5. Mask all but last 4 digits of card numbers.

Next: PIP →

Related Topics

Frequently Asked Questions about RegEx

What is RegEx in Python?

RegEx is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn RegEx?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn RegEx.

Why is RegEx important in Python?

RegEx is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.