Python6 min read
Python Regular Expressions
Search and manipulate text using regex patterns.
Michael Brown
December 18, 2025
0.0k0
Master text pattern matching.
Basic Search
```python import re
text = "My phone is 555-1234"
Find pattern match = re.search(r"\d{3}-\d{4}", text) if match: print(match.group()) # 555-1234 ```
Find All Matches
```python import re
text = "Contact: john@example.com or sarah@test.com"
Find all emails emails = re.findall(r"[\w.-]+@[\w.-]+", text) print(emails) # ['john@example.com', 'sarah@test.com'] ```
Replace Text
```python import re
text = "My number is 123-456-7890"
Replace phone number new_text = re.sub(r"\d{3}-\d{3}-\d{4}", "XXX-XXX-XXXX", text) print(new_text) # My number is XXX-XXX-XXXX ```
Common Patterns
```python import re
Email validation email = "user@example.com" if re.match(r"^[\w.-]+@[\w.-]+\.\w+$", email): print("Valid email")
Phone number phone = "555-1234" if re.match(r"^\d{3}-\d{4}$", phone): print("Valid phone")
URL url = "https://www.example.com" if re.match(r"^https?://", url): print("Valid URL") ```
Remember
- \d for digits, \w for word chars - * for 0+, + for 1+, ? for 0 or 1 - Use raw strings (r"") for patterns
#Python#Intermediate#Regex