Regex Pattern Matching

Use regular expressions to match and extract text.

Code

Python
import re

text = "Contact: john@example.com or jane@test.org"
pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"

matches = re.findall(pattern, text)
print("Emails:", matches)

# Replace
new_text = re.sub(pattern, "[EMAIL]", text)
print(new_text)

Line-by-line explanation

Expected output

Emails: ['john@example.com', 'jane@test.org']

Related snippets

Related DuskTools