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 match
  • Practical 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 solved
    Exercise 1 of 3easy
    โฑ 00:00

    Extract All IP Addresses

    Find all IP addresses in the log string.
    Expected output: ['192.168.1.1', '10.0.0.5', '172.16.0.1']
    solution.py
    1 / 3
    Exercise 2 of 3medium
    โฑ 00:00

    Validate Email Format

    Check if a string looks like a valid email (has @ and a dot after it).
    Expected output:alice@example.com: validnot-an-email: invalidbob@company.org: valid
    solution.py
    2 / 3
    Exercise 3 of 3medium
    โฑ 00:00

    Extract Log Timestamps

    Extract all timestamps in HH:MM:SS format from the log.
    Expected output: ['09:15:32', '09:15:45', '09:16:01']
    solution.py
    3 / 3
    Solve all 3 exercises to unlock completion