Python Regular Expressions: Complete Guide to the 're' Module

A Regular Expression (Regex) is a powerful tool for pattern matching and text parsing. With regex, you can validate email addresses, verify telephone numbers, scrape specific text patterns from web pages, and sanitize user input with surgical precision using Python's built-in re module.


1. Common Regex Metacharacters Reference

Metacharacter Matches Example Pattern
.Any single character except newline.c.t matches cat, cot
^ and $Start of string (^) and End of string ($).^Hello$
* / + / ?0 or more (*) / 1 or more (+) / 0 or 1 (?).d+ (1 or more digits)
d / DAny digit [0-9] / Any non-digit.d{10} (10-digit phone)
w / sAlphanumeric word character / Whitespace.w+@w+.w+
[...]Character set.[a-zA-Z] (any letter)

2. Primary re Functions: search(), findall(), sub()

import re

text = "Contact support at info@veewom.com or sales@veewom.com by 2026-11-04."

# 1. re.search(): Find first match
phone_pattern = r"d{4}-d{2}-d{2}"
match = re.search(phone_pattern, text)
if match:
    print("Found Date:", match.group())  # 2026-11-04

# 2. re.findall(): Extract all matching instances
email_pattern = r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+"
emails = re.findall(email_pattern, text)
print("Extracted Emails:", emails)
# ['info@veewom.com', 'sales@veewom.com']

# 3. re.sub(): Find and replace text
censored = re.sub(email_pattern, "[EMAIL HIDDEN]", text)
print("Sanitized Text:", censored)

3. Practical Validation: Indian Phone Number Validator

def is_valid_indian_mobile(phone: str) -> bool:
    # 10-digit mobile number starting with 6, 7, 8, or 9:
    pattern = r"^[6-9]d{9}$"
    return bool(re.match(pattern, phone))

print(is_valid_indian_mobile("9876543210"))  # True
print(is_valid_indian_mobile("1234567890"))  # False (Starts with 1)
print(is_valid_indian_mobile("987654"))       # False (Too short)

Frequently Asked Questions (FAQ)

Why should raw string notation (r"") always be used for regex patterns?

Standard Python strings use backslashes for escape characters (like or ). Using raw string syntax r"d+" ensures Python passes literal backslashes directly to the regex engine without attempting to decode escape sequences.
Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!