35
I need to extract data from text using patterns. How do I use regex in Python?
Loading...
Q&A · Answered
I need to extract data from text using patterns. How do I use regex in Python?
Accepted answer
import re
text = "Email: user@example.com, Phone: 123-456-7890"
# Find all matches
emails = re.findall(r'[\w.-]+@[\w.-]+', text)
# Search for pattern
match = re.search(r'\d{3}-\d{3}-\d{4}', text)
if match:
phone = match.group()
# Replace
new_text = re.sub(r'\d+', 'XXX', text)
# Compile for reuse
email_pattern = re.compile(r'[\w.-]+@[\w.-]+')
matches = email_pattern.findall(text)Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.