advancedAdvanced Topics

Regular Expressions

Pattern matching with the re module.

01Basic Pattern Matching

Use the re module for powerful string pattern matching.

Python
1import re
2
3text = "Contact: alice@example.com or bob@test.org"
4
5# Find all emails
6emails = re.findall(r'[\w.]+@[\w.]+', text)
7print(emails)
8
9# Search and replace
10cleaned = 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 re
2
3pattern = r'(\d{4})-(\d{2})-(\d{2})'
4text = "Today is 2026-06-08 and tomorrow is 2026-06-09"
5
6match = 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