advancedAdvanced Topics
Regular Expressions
Pattern matching with the re module.
In this lesson
01Basic Pattern Matching
Use the re module for powerful string pattern matching.
Python
1import re23text = "Contact: alice@example.com or bob@test.org"45# Find all emails6emails = re.findall(r'[\w.]+@[\w.]+', text)7print(emails)89# Search and replace10cleaned = re.sub(r'\d+', 'NUM', "I have 3 cats and 12 dogs")11print(cleaned)
Output
['alice@example.com', 'bob@test.org'] I have NUM cats and NUM dogs
02Groups and Matching
Extract parts of matches using groups.
Python
1import re23pattern = r'(\d{4})-(\d{2})-(\d{2})'4text = "Today is 2026-06-08 and tomorrow is 2026-06-09"56match = re.search(pattern, text)7if match:8 print(f"Full: {match.group(0)}")9 print(f"Year: {match.group(1)}")10 print(f"Month: {match.group(2)}")11 print(f"Day: {match.group(3)}")
Output
Full: 2026-06-08 Year: 2026 Month: 06 Day: 08