What are Regular Expressions?

Regular expressions (regex) are patterns for matching and manipulating text. Python's re module provides regex functionality.

Basic Pattern Matching

Use re.search() to find patterns:

import re

text = "Contact: [email protected]"
pattern = r'\b\w+@\w+\.\w+\b'
match = re.search(pattern, text)
if match:
    print(match.group())  # [email protected]

Common Patterns

Common regex patterns:

\\d          # Any digit
\\d{3}       # Exactly 3 digits
\\w          # Word character
\\w+         # One or more word characters
.            # Any character
*            # Zero or more
+            # One or more
^            # Start of string
$            # End of string

Finding All Matches

Use re.findall():

text = "Prices: $10, $20, $30"
pattern = r'\\$\\d+'
prices = re.findall(pattern, text)
print(prices)  # ['$10', '$20', '$30']

Replacing Text

Use re.sub():

text = "Hello World"
new_text = re.sub(r'World', 'Python', text)
print(new_text)  # Hello Python

Compiled Patterns

Compile patterns for better performance:

pattern = re.compile(r'\\d+')
matches = pattern.findall("123 abc 456")
print(matches)  # ['123', '456']

Best Practices

  • Use raw strings: r'pattern' to avoid escaping
  • Compile patterns: For repeated use
  • Test patterns: Use online regex testers
  • Keep patterns simple: Complex regex is hard to maintain

Next Steps

Practice with email validation and text parsing examples.