Regular Expressions in Python with the re Module
Regular expressions (regex) let you search, validate and transform text using patterns. Python's re module provides search, substitution, extraction and string splitting.
Core re Module Functions
import re
text = "Contact support@company.com or admin@example.org for more info."
# re.search — First match (anywhere in string)
m = re.search(r'\b[\w.-]+@[\w.-]+\.\w{2,}\b', text)
if m:
print(f"Email found: {m.group()}") # support@company.com
# re.findall — All matches
emails = re.findall(r'\b[\w.-]+@[\w.-]+\.\w{2,}\b', text)
print(f"Emails: {emails}")
# re.match — Only at start of string
m = re.match(r'\d+', "42 items in stock")
if m:
print(f"Leading number: {m.group()}") # 42
# re.fullmatch — Exact full match
valid = re.fullmatch(r'\d{4}-\d{2}-\d{2}', "2024-06-15")
print(f"Valid date: {valid is not None}")
Substitute with re.sub
import re
text = "Price: $123.45, discount: $10.00, total: $113.45"
# Replace all prices
result = re.sub(r'\$[\d.]+', '[PRICE]', text)
print(result)
# Price: [PRICE], discount: [PRICE], total: [PRICE]
# Substitute with function (uppercase)
text2 = "hello world, hello python"
upped = re.sub(r'\bhello\b', lambda m: m.group().upper(), text2)
print(upped) # HELLO world, HELLO python
# Strip HTML tags
html = "<h1>Title</h1><p>Text with <strong>bold</strong> and <em>italic</em>.</p>"
clean = re.sub(r'<[^>]+>', '', html)
print(clean) # Title Text with bold and italic.
Groups and Capture
import re
# Capture groups
dates = ["2024-06-15", "2023-12-31", "2025-01-01"]
pattern = re.compile(r'(\d{4})-(\d{2})-(\d{2})')
for date in dates:
m = pattern.match(date)
if m:
year, month, day = m.groups()
print(f"Year={year} Month={month} Day={day}")
# Named groups
text = "Name: Alice Smith | Email: alice@mail.com | Phone: 555-123-4567"
m = re.search(r'Name: (?P<name>[\w\s]+) \| Email: (?P<email>\S+)', text)
if m:
print(f"Name: {m.group('name')}")
print(f"Email: {m.group('email')}")
# Parse URLs
url = "https://www.example.com:8080/path/page?param=value#section"
m = re.match(r'(?P<scheme>https?)://(?P<host>[^:/]+)(?::(?P<port>\d+))?(?P<path>/[^?#]*)', url)
if m:
for k, v in m.groupdict().items():
if v: print(f" {k}: {v}")
Validate Common Formats
import re
PATTERNS = {
"email": r'^[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}$',
"phone": r'^[+]?[\d\s\-().]{7,15}$',
"url": r'^https?://[\w\-]+(\.[\w\-]+)+(/[\w\-./?%&=]*)?$',
"ip": r'^(\d{1,3}\.){3}\d{1,3}$',
"zip_us": r'^\d{5}(-\d{4})?$',
"credit": r'^\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}$',
"date_iso": r'^\d{4}-\d{2}-\d{2}$',
}
def validate(value, kind):
pattern = PATTERNS.get(kind)
if not pattern: return None
ok = bool(re.fullmatch(pattern, value.strip()))
print(f" [{kind}] '{value}': {'VALID' if ok else 'INVALID'}")
return ok
validate("user@example.com", "email")
validate("not-an-email", "email")
validate("https://mysite.com", "url")
validate("192.168.1.1", "ip")
validate("4111 1111 1111 1111", "credit")
Advanced Operations
import re
# re.split — Split by pattern
text = "apples, oranges;grapes|melons and watermelons"
items = re.split(r'[,;|\s]+', text)
items = [i.strip() for i in items if i.strip()]
print(items)
# Compile for reuse (faster)
price_pattern = re.compile(r'\b(\d+(?:\.\d{1,2})?)\s*USD', re.IGNORECASE)
invoice = "Widget A: 29.99 USD, Widget B: 14.50 usd, Total: 44.49 USD"
prices = price_pattern.findall(invoice)
print(f"Prices: {prices}") # ['29.99', '14.50', '44.49']
# Lookahead and lookbehind
log = "INFO: connection OK\nERROR: timeout\nWARNING: low memory\nERROR: disk full"
errs = re.findall(r'(?<=ERROR: ).+', log)
print(f"Errors: {errs}") # ['timeout', 'disk full']
Additional Resource
For converting and processing text files between different formats without any coding, use KaijuConverter — free and no registration required.
Related conversions
Frequent conversions across the catalogue: