본문 바로가기
Computer Science/Python

[Python] re 모듈: 정규 표현식

by rnasterofmysea 2025. 4. 4.
반응형

 

[Python] re  정규 표현식으로 문자열 표현하기

파이썬에서 정규 표현식(Regular Expression)을 다루기 위한 대표적인 도구가 바로 re 모듈입니다. 이 글에서는 re 모듈의 주요 기능부터 실용적인 예제, 성능 팁까지 정리해 드립니다. 정규표현식 초보자도 쉽게 따라올 수 있도록 예시와 함께 설명하니 천천히 따라와 주세요!


✅ 1. 정규 표현식 메타문자 정리

메타문자 의미 예시

. 줄바꿈 제외 아무 문자 a.c → "abc", "a c"
^ 문자열의 시작 ^Hello
$ 문자열의 끝 world$
* 0회 이상 반복 a*b → "b", "aab"
+ 1회 이상 반복 a+b → "ab", "aab"
? 0회 또는 1회 a?b → "b", "ab"
{n} n회 반복 a{3} → "aaa"
{n,m} n~m회 반복 a{2,4} → "aa", "aaa"
[] 문자 집합 [abc] → "a", "b", "c"
` ` OR 연산
() 그룹화 (ab)+ → "ab", "abab"

🔎 2. 주요 함수 소개

🎯 검색 함수

re.search(pattern, string)
re.match(pattern, string)
re.findall(pattern, string)
re.finditer(pattern, string)
import re

text = "Python 3.10 released on October 4, 2021"

print(re.search(r'\d+\.\d+', text).group())  # 3.10
print(re.match(r'Python', text).group())     # Python
print(re.findall(r'\d+', text))              # ['3', '10', '4', '2021']

for m in re.finditer(r'\d+', text):
    print(m.group(), m.span())

🛠️ 치환 함수

re.sub(pattern, replacement, string, count=0)
re.sub(r'\d+', 'X', text)          # 'Python X.X released on October X, X'
re.sub(r'\d+', 'X', text, count=2) # 'Python X.X released on October 4, 2021'

✂️ 분할 함수

re.split(pattern, string)
re.split(r'\W+', text)
# ['Python', '3', '10', 'released', 'on', 'October', '4', '2021']

📌 3. 정규식 컴파일

반복 사용 시 성능 향상을 위해 컴파일!

pattern = re.compile(r'\b[A-Z][a-z]+\b')
print(pattern.findall("Python Java C++ JavaScript"))  # ['Python', 'Java', 'JavaScript']

🧠 4. 고급 기능

🎯 그룹 캡처

text = "John: 30, Jane: 25"
matches = re.findall(r'(\w+):\s(\d+)', text)
for name, age in matches:
    print(f"{name} is {age} years old")

🎯 비캡처 그룹 (?:...)

re.findall(r'(?:\w+):\s(\d+)', text)  # ['30', '25']

🔍 전방/후방 탐색

re.findall(r'\w+(?=:)', text)       # ['John', 'Jane']
re.findall(r'(?<=:\s)\d+', text)    # ['30', '25']

💡 5. 실전 예제

✅ 이메일 검증

def is_valid_email(email):
    return bool(re.match(r'^[\w._%+-]+@[\w.-]+\.[a-zA-Z]{2,}$', email))

is_valid_email("test@example.com")  # True
is_valid_email("invalid.email@")    # False

🧹 HTML 태그 제거

html = "<p>This is <b>bold</b> text</p>"
re.sub(r'<[^>]+>', '', html)  # 'This is bold text'

🗂️ 로그 분석

log = """
[ERROR] 2023-01-15 14:30:22 - Connection timeout
[INFO] 2023-01-15 14:31:10 - User logged in
[WARNING] 2023-01-15 14:32:45 - Disk space low
"""

for m in re.finditer(r'\[(\w+)\]\s([\d-]+\s[\d:]+)\s-\s(.*)', log):
    level, time, msg = m.groups()
    print(f"{level}: {msg} at {time}")

⚙️ 6. 성능 팁

1. re.compile() 적극 활용

2. 게으른 수량자 (.*?) 사용 고려

3. 백트래킹 문제 피하기

# 성능 문제 발생 가능
re.match(r'(a+)+$', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaa!')

# 개선된 버전
re.match(r'a+$', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaa!')

⚠️ 7. 주의사항

  • 특수문자는 이스케이프 필수! (\.)
  • 유니코드 처리 시 re.UNICODE 사용
re.search(r'\.com', 'example.com')          # True
re.findall(r'\w+', 'こんにちは', flags=re.UNICODE)  # ['こんにちは']

 

 

반응형