Site Tools


import-re

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

  • re.search(pattern, text): find first match
  • re.match(pattern, text): match at start of string
  • re.findall(pattern, text): find all matches
  • re.sub(pattern, repl, text): replace matches
  • re.split(pattern, text): split by pattern
  • re.compile(pattern): create reusable regex object
  • pattern.finditer(text): iterate over matches with position
import-re.md · Last modified: by 127.0.0.1