reRegular expressions provide powerful string matching, extraction, and substitution capabilities via Python's built-in re module.
flowchart TD
A["Raw Pattern String r'...'"] --> B["re.compile(pattern)"]
B --> C["Regex Pattern Object"]
C --> D["Search / Match / Findall Operation"]
D --> E["Match Object (groups, start, end)"]
rere.search(pattern, string): Scans string for first pattern location; returns a Match object or None.re.findall(pattern, string): Returns all non-overlapping matches as a list of strings/tuples.re.sub(pattern, replacement, string): Replaces pattern occurrences with replacement string.re.compile(pattern): Pre-compiles regex pattern into a reusable Regex Object for performance.import re
from typing import List, Dict
def extract_contact_info(text: str) -> Dict[str, List[str]]:
# Use raw string r'...' to prevent backslash escaping issues
email_pattern = re.compile(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}')
phone_pattern = re.compile(r'\d{3}[-.]?\d{3}[-.]?\d{4}')
emails = email_pattern.findall(text)
phones = phone_pattern.findall(text)
# Clean telephone formats via re.sub
cleaned_phones = [re.sub(r'[-.]', '', p) for p in phones]
return {
"emails": emails,
"phones": cleaned_phones
}
if __name__ == "__main__":
raw_document = """
For security support, contact [email protected] or [email protected].
Emergency hotline: 555-123-4567 or direct line 555.987.6543.
"""
info = extract_contact_info(raw_document)
print("Extracted Emails:", info["emails"])
print("Extracted Cleaned Phones:", info["phones"])
r"...": Always prefix regex pattern strings with r to prevent Python from parsing , , or as escape sequences.re.compile() outside loops when evaluating the same pattern against thousands of strings.(a+)+ which cause exponential CPU execution times on non-matching strings.Write a regex pattern that validates whether a given string is a valid IPv4 address (four dot-separated integers from 0 to 255).
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With