Table of Contents

import re

import re is a Python import that provides regular expression matching. Use it to search, match, replace, or split strings based on patterns.

Example

# Python
# description: regex matching, substitution, splitting
 
import re
 
text = "Contact: [email protected] or [email protected]"
 
# Find all email addresses
emails = re.findall(r"\b[a-z]+@[a-z.]+\b", text)
print(emails)  # ['[email protected]', '[email protected]']
 
# Check if pattern matches
if re.search(r"@example\.com", text):
    print("Found example.com address")
 
# Replace pattern
result = re.sub(r"@\S+", "@hidden", text)
print(result)  # Contact: alice@hidden or bob@hidden
 
# Split by pattern
parts = re.split(r"[,:]", "one,two:three")
print(parts)  # ['one', 'two', 'three']
 
# Compiled regex for repeated use
pattern = re.compile(r"\d+")
numbers = pattern.findall("Page 1, 2, 3")
print(numbers)  # ['1', '2', '3']

Common functions