🔍

How to Use Regular Expressions in Python

PythonIntermediate

Pattern matching with regular expressions.

Code Example

Python
import re

text = "Contact: alice@example.com or bob@test.org"

# Find email addresses
emails = re.findall(r'[\w\.-]+@[\w\.-]+', text)
print(f"Emails: {emails}")

# Search for pattern
if re.search(r'\d+', "Order 12345"):
    print("\nFound numbers in text")

# Replace pattern
cleaned = re.sub(r'\d+', '#', "Phone: 123-456-7890")
print(f"\nCleaned: {cleaned}")

# Match at start
if re.match(r'^Hello', "Hello World"):
    print("\nStarts with Hello")

# Split by pattern
parts = re.split(r'[,;]', "apple,banana;cherry")
print(f"\nSplit: {parts}")

# Extract groups
pattern = r'(\w+)@(\w+)'
match = re.search(pattern, "user@domain")
if match:
    print(f"\nUser: {match.group(1)}, Domain: {match.group(2)}")

Explanation

The re module provides regex operations. findall() finds all matches, search() finds first match, sub() replaces, split() splits by pattern.

Related Tutorials