Python

Regular Expressions in Python

Master Python regex with the re module - match, search, findall, sub, and compile patterns.

Try Regex Tester →

Code Example

import re

# Basic patterns
pattern = r'^[\w.-]+@[\w.-]+\.[a-z]{2,}$'

# Match at beginning
match = re.match(r'Hello', 'Hello World')
if match:
    print(match.group())  # 'Hello'

# Search anywhere
search = re.search(r'\d+', 'Price: $99')
print(search.group())  # '99'

# Find all matches
text = 'Contact info@example.com or support@test.com'
emails = re.findall(r'[\w.-]+@[\w.-]+\.[a-z]{2,}', text)
# ['info@example.com', 'support@test.com']

# Replace
result = re.sub(r'secret\d+', '***', 'password: secret123')
# 'password: ***'

# Compile for reuse
email_pattern = re.compile(r'^[\w.-]+@[\w.-]+\.[a-z]{2,}$', re.IGNORECASE)
email_pattern.match('user@example.com')

# Groups
date_match = re.match(r'(\d{4})-(\d{2})-(\d{2})', '2025-01-27')
year, month, day = date_match.groups()

# Named groups
pattern = r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})'
match = re.match(pattern, '2025-01-27')
print(match.group('year'))  # '2025'
Key Points: Python re module provides match() for start, search() for anywhere, findall() for all matches. Use r"" raw strings for patterns.

Related Examples

More Python Examples