Skip to content
Python

Regex Matching

Perform regex matching using the re module.

By EZ4Code Team
regexregex

Code

import re

# Find all matches
emails = re.findall(r"[\w.+-]+@[\w-]+\.[\w.]+", text)

# Replace
result = re.sub(r"\d+", "N", "abc123def456")

# Group matching
m = re.match(r"(\w+)-(\d+)", "item-42")
if m:
    print(m.group(1), m.group(2))

# Named group
m = re.match(r"(?P<name>\w+):(?P<value>\d+)", "age:18")
print(m.groupdict())

Explanation

The re module provides regex operations like find, replace, and grouping.

More Python Snippets