Lesson 45/48 ยท ๐ Working with the Real World
๐ Working with the Real WorldLesson 45/48
Phase 8 ยท Working with the Real World22 min
Regular Expressions: Pattern Matching
re.search(), re.findall(), find anything in text
Regular expressions (regex) let you search, match, and extract patterns from text. They look intimidating at first but 5 patterns cover 90% of real-world use cases.
Basics: search and findallpython
import re
log = "Error at 192.168.1.100: Connection timeout at 10.0.0.1"
# re.search(), find first match
match = re.search(r'\d+\.\d+\.\d+\.\d+', log)
if match:
print(match.group()) # 192.168.1.100
# re.findall(), find ALL matches
ips = re.findall(r'\d+\.\d+\.\d+\.\d+', log)
print(ips) # ['192.168.1.100', '10.0.0.1']The 5 most useful patterns:
\d+, one or more digits\w+, one or more word characters (letters, digits, underscore)\s+, one or more whitespace characters[A-Z]+, one or more uppercase letters.*?, any characters, minimal matchPractical patternspython
import re
# Extract email addresses
text = "Contact alice@example.com or bob@company.org for help"
emails = re.findall(r'[\w.+-]+@[\w-]+\.[\w.]+', text)
print(emails) # ['alice@example.com', 'bob@company.org']
# Extract dates (YYYY-MM-DD format)
log = "Deploy started 2026-03-09, completed 2026-03-10"
dates = re.findall(r'\d{4}-\d{2}-\d{2}', log)
print(dates) # ['2026-03-09', '2026-03-10']
# Replace patterns
sanitized = re.sub(r'\d+\.\d+\.\d+\.\d+', '[REDACTED]', log)๐In the Real World...
Parsing log files for error patterns and IP addresses. Extracting versions from package lists. Validating config values. Regex is the scalpel of text processing.
Practice Exercises
0/3 solvedExercise 1 of 3easy
โฑ 00:00Extract All IP Addresses
Find all IP addresses in the log string.
Expected output:
Expected output:
['192.168.1.1', '10.0.0.5', '172.16.0.1']solution.py
1 / 3
Exercise 2 of 3medium
โฑ 00:00Validate Email Format
Check if a string looks like a valid email (has @ and a dot after it).
Expected output:
Expected output:
alice@example.com: validnot-an-email: invalidbob@company.org: validsolution.py
2 / 3
Exercise 3 of 3medium
โฑ 00:00Extract Log Timestamps
Extract all timestamps in HH:MM:SS format from the log.
Expected output:
Expected output:
['09:15:32', '09:15:45', '09:16:01']solution.py
3 / 3
Solve all 3 exercises to unlock completion