📡 You're offline — showing cached content
New version available!
Quick Access
SQL Intermediate

Python Regular Expressions: re Module Complete Guide

Master Python re module — search, match, findall, sub, compile, named groups, lookahead/lookbehind, and a validation pattern library.

EzyCoders Admin December 22, 2025 10 min read 0 views
Python Regular Expressions re Module Guide
Share: Twitter LinkedIn WhatsApp

Python Regular Expressions

Python's re module provides full PCRE support. From simple validation to complex text processing pipelines, regex is essential in every Python developer's toolkit.

import re

text = "Contact: rahul@ezycoders.in or visit https://ezycoders.in"

# search: first match anywhere
m = re.search(r'https?://[\w./]+', text)
if m: print(m.group())   # https://ezycoders.in

# findall: list of all matches
emails = re.findall(r'[\w.+-]+@[\w-]+\.[a-z]{2,}', text, re.IGNORECASE)
# ['rahul@ezycoders.in']

# sub: replace
clean = re.sub(r'\s+', ' ', "  too   many   spaces  ").strip()

# compile: reuse pattern (faster in loops)
email_pat = re.compile(r'[\w.+-]+@[\w-]+\.[a-z]{2,}', re.IGNORECASE)

Groups and Named Captures

date_pat = re.compile(r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})')
m = date_pat.search('Published: 2026-03-15')
if m:
    print(m.group('year'))   # '2026'
    print(m.groupdict())     # {'year':'2026','month':'03','day':'15'}

# Replace with function
result = re.sub(r'\d+', lambda m: str(int(m.group()) * 2), 'I have 5 cats')
# 'I have 10 cats'

Common Validation Patterns

PATTERNS = {
    'email':    r'^[\w.+-]+@[\w-]+\.[a-z]{2,}$',
    'phone_in': r'^[6-9]\d{9}$',
    'url':      r'^https?://[\w.-]+\.[a-z]{2,}',
    'slug':     r'^[a-z0-9]+(?:-[a-z0-9]+)*$',
    'pan_card': r'^[A-Z]{5}[0-9]{4}[A-Z]{1}$',
}

def validate(pattern_name: str, value: str) -> bool:
    pattern = PATTERNS.get(pattern_name)
    return bool(re.match(pattern, value, re.IGNORECASE))

Q: re.match vs re.search vs re.fullmatch?

match: only at START. search: anywhere in string. fullmatch: entire string must match. For validation always use fullmatch or match with ^ and $ anchors to avoid partial matches.

EzyCoders Admin
Written by
EzyCoders Admin

Team Lead and Full-Stack Developer with experience in PHP, JavaScript, SQL, DSA, and System Design. Passionate about software engineering, scalable web technologies, and helping developers prepare for coding interviews and tech careers through practical tutorials and professional guidance.

Comments (0)

No comments yet. Be the first!

Leave a Comment