Chapter 10: Advanced Topics / Lesson 59

Regular Expressions

Introduction to Regular Expressions

Regular expressions (regex) are powerful pattern-matching tools. Python's re module provides functions to search, match, and manipulate strings using patterns. Regex is useful for validation, parsing, and text processing.

Regular expressions use special characters to define patterns that match text in various ways.

Basic Pattern Matching

Use re.search() to find patterns in strings:

regex_basic.py
import re # Search for pattern text = "Hello, my email is alice@example.com" pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}" # Email pattern match = re.search(pattern, text) if match: print(match.group()) # alice@example.com # Match at start of string result = re.match(r"Hello", text) print(result) # Match object # Find all matches numbers = "I have 5 apples and 3 oranges" matches = re.findall(r"\\d+", numbers) print(matches) # ['5', '3']

Common Regex Patterns

Here are some common regex patterns:

regex_patterns.py
# Common patterns # \\d - digit (0-9) # \\w - word character (a-z, A-Z, 0-9, _) # \\s - whitespace # . - any character # * - zero or more # + - one or more # ? - zero or one # ^ - start of string # $ - end of string import re # Match phone number phone = "Call me at 555-1234" pattern = r"\\d{3}-\\d{4}" match = re.search(pattern, phone) print(match.group() if match else "Not found") # Match words starting with capital text = "Hello World Python" matches = re.findall(r"[A-Z][a-z]+", text) print(matches) # ['Hello', 'World', 'Python']

Regex Methods

Common regex methods in Python:

  • re.search() - Find first match anywhere
  • re.match() - Match at start of string
  • re.findall() - Find all matches
  • re.sub() - Replace matches
  • re.split() - Split by pattern

Best Practices

✅ Regex Tips

• Use raw strings (r"...") for patterns

• Test regex patterns with simple examples first

• Be careful with special characters - escape them with \\

• Use regex for complex patterns, simple string methods for simple cases

• Regex can be complex - document your patterns

🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...