Introduction
Regular expressions (regex) are powerful tools for pattern matching and text manipulation. Python’s built-in re module provides full regex support. This cheat sheet covers all major patterns and functions you’ll need.
Basic Pattern Matching
import re
# Search for a pattern
result = re.search(r’\d+’, ‘Order 1234 shipped’)
if result:
print(result.group()) # 1234
# Find all matches
result = re.findall(r’\d+’, ‘Call 555-1234 or 555-5678’)
print(result) # [‘555’, ‘1234’, ‘555’, ‘5678’]
Common Regex Patterns
# Email validation
email_pattern = r’^[\w.-]+@[\w.-]+\.\w{2,}$’
print(bool(re.match(email_pattern, ‘user@example.com’))) # True
# Phone number
phone = r’\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}’
print(re.findall(phone, ‘Call 555-123-4567 now’)) # [‘555-123-4567’]
# URL
url_pattern = r’https?://[\w./%-]+’
Substitution with re.sub
import re
# Remove all digits
clean = re.sub(r’\d’, ”, ‘abc123def456’)
print(clean) # abcdef
# Replace spaces with underscores
slug = re.sub(r’\s+’, ‘_’, ‘Hello World Foo’)
print(slug) # Hello_World_Foo
Groups and Capture
# Extract groups
match = re.search(r'(\d{4})-(\d{2})-(\d{2})’, ‘2024-01-15’)
if match:
year, month, day = match.groups()
print(year, month, day) # 2024 01 15
Conclusion
This guide covered “Python Regex Cheat Sheet – Regular Expressions with Examples”. Bookmark this page and keep it as your go-to reference. If you found this helpful, share it with fellow developers and check out more snippets on programsnippet.com!

Leave a Reply Cancel reply