Skip to content
Python

정규식 매칭

re 모듈을 사용해 정규식 매칭 수행.

#regex#regex

Code

python
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())