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\dreaches the regex engine instead of Python interpreting the backslash.
Character building blocks
| Pattern | Matches |
|---|---|
\d / \w / \s | digit / word char / whitespace |
. | any character |
[aeiou] | one listed char; [a-z0-9] ranges |
[^0-9] | NOT a digit |
^…$ | start / end anchors |
colou?r | optional (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
| Function | Succeeds when pattern matches… |
|---|---|
match | starts at position 0 |
search | anywhere in string |
fullmatch | the 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
- Extract every word ≥5 letters from a paragraph.
- Validate five phone shapes with fullmatch.
- Named-group parse "name=Alice;age=36".
- Slugify three titles via sub.
- 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.