How to use regular expressions in Python

Answered
Jan 05, 2026 311 views 1 answers
35

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

N
Asked by noor_code
Gold 255 rep

1 Answer

7

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)
Y
Answered by youssef_net 1 week, 2 days ago
Platinum 311 rep

Your Answer

You need to be logged in to answer questions.

Log In to Answer

Related Questions

Hot Questions

No hot questions available.