The re module provides powerful pattern matching and text manipulation capabilities.
import re
# 1. Email validation
email = "user@example.com"
pattern = r"^[\w\.-]+@[\w\.-]+\.\w+$"
if re.match(pattern, email):
print("Valid email")
# 2. Phone number extraction
text = "Call me at 123-456-7890 or 987-654-3210"
phones = re.findall(r"\d{3}-\d{3}-\d{4}", text)
print(phones) # ['123-456-7890', '987-654-3210']
# 3. Password validation (8+ chars, letter + number)
password = "secure123"
if re.match(r"^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$", password):
print("Strong password")
# 4. Extract URLs from text
text = "Visit https://example.com or http://test.org"
urls = re.findall(r"https?://[\w\.-]+\.\w+", text)
print(urls) # ['https://example.com', 'http://test.org']
# 5. Replace/clean text
text = "Hello World! How are you?"
cleaned = re.sub(r"\s+", " ", text) # Replace multiple spaces with one
print(cleaned) # "Hello World! How are you?"
# 6. Remove HTML tags
html = "
Hello World
"
plain_text = re.sub(r"<.*?>", "", html)
print(plain_text) # "Hello World"
# 7. Split by multiple delimiters
text = "apple,banana;orange|grape"
fruits = re.split(r"[,;|]", text)
print(fruits) # ['apple', 'banana', 'orange', 'grape']
# 8. Extract hashtags
tweet = "Loving #Python and #Coding today!"
hashtags = re.findall(r"#\w+", tweet)
print(hashtags) # ['#Python', '#Coding']
# 9. Validate date format (YYYY-MM-DD)
date = "2025-11-09"
if re.match(r"^\d{4}-\d{2}-\d{2}$", date):
print("Valid date format")
# 10. Compile pattern for reuse (more efficient)
email_pattern = re.compile(r"^[\w\.-]+@[\w\.-]+\.\w+$")
print(email_pattern.match("test@example.com")) # Match object
print(email_pattern.match("invalid-email")) # None
# 11. Groups and capturing
phone = "123-456-7890"
match = re.search(r"(\d{3})-(\d{3})-(\d{4})", phone)
if match:
area_code = match.group(1) # 123
print(f"Area code: {area_code}")
print(match.groups()) # ('123', '456', '7890')
# 12. Case-insensitive matching
text = "Python is AWESOME"
if re.search(r"python", text, re.IGNORECASE):
print("Found 'python' (case-insensitive)")