Skip to content

Q&A · Answered

How to use regular expressions in Python

asked 9 months, 1 week ago 733 views 1 answer
35

I need to extract data from text using patterns. How do I use regex in Python?

1 Answer

One accepted
7

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago

Basic regex operations

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)

Compiled patterns

# Compile for reuse
email_pattern = re.compile(r'[\w.-]+@[\w.-]+')
matches = email_pattern.findall(text)

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.