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 matchre.match(pattern, text): match at start of stringre.findall(pattern, text): find all matchesre.sub(pattern, repl, text): replace matchesre.split(pattern, text): split by patternre.compile(pattern): create reusable regex objectpattern.finditer(text): iterate over matches with position
import-re.md · Last modified: by 127.0.0.1
