Regex Pattern Matching
Use regular expressions to match and extract text.
Code
Python
import re text = "Contact: [email protected] or [email protected]" 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
- 1.Import the re module.
- 2.Define a regex pattern (email example).
- 3.re.findall() returns all non-overlapping matches.
- 4.re.sub() replaces matches with a string.
Expected output
Emails: ['[email protected]', '[email protected]']