Python re Module
import re
text = 'Hello World 123'
print(re.findall(r'\d+', text)) # ['123']
print(re.findall(r'[a-zA-Z]+', text)) # ['Hello', 'World']
Common Patterns
# Email validation
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
print(bool(re.match(email_pattern, 'user@example.com'))) # True
# Extract hashtags
hashtags = re.findall(r'#\w+', '#coding #python #webdev')
Groups and Named Groups
import re
date_pattern = r'(?P\d{4})-(?P\d{2})-(?P\d{2})'
match = re.search(date_pattern, '2026-07-15')
print(match.group('year')) # 2026
print(match.group('month')) # 07
Substitution
# Clean phone numbers
dirty = '(555) 123-4567'
clean = re.sub(r'[^\d]', '', dirty)
print(clean) # 5551234567
# Slugify
def slugify(text):
text = text.lower().strip()
text = re.sub(r'[^\w\s-]', '', text)
text = re.sub(r'[\s_-]+', '-', text)
return text
Ready to Level Up Your Coding Skills?
Join Coderz Club and learn to code with challenges, battles, and an AI mentor.
Join Coderz Club Free →