IT

파이썬 정규표현식 (Regular Expressions)

carnival6103 2025. 2. 8. 08:11
반응형

정규표현식(Regular Expressions, regex)은 문자열에서 특정 패턴을 찾거나, 대체하거나, 추출하는 데 사용되는 강력한 도구입니다. 파이썬에서는 re 모듈을 사용하여 정규표현식을 다룰 수 있습니다. 아래는 정규표현식의 기본 개념과 예시입니다.

1. re 모듈 임포트

먼저 re 모듈을 임포트합니다.

import re

2. 기본 패턴

  • .: 임의의 한 문자
  • ^: 문자열의 시작
  • $: 문자열의 끝
  • *: 0회 이상 반복
  • +: 1회 이상 반복
  • ?: 0회 또는 1회 반복
  • []: 문자 집합
  • |: OR 연산자
  • (): 그룹화

3. 정규표현식 함수

  • re.match(): 문자열의 시작에서 패턴이 일치하는지 확인
  • re.search(): 문자열 전체에서 패턴이 일치하는지 확인
  • re.findall(): 문자열에서 패턴과 일치하는 모든 부분을 리스트로 반환
  • re.sub(): 문자열에서 패턴과 일치하는 부분을 다른 문자열로 대체

4. 예시

  1. re.match() 예시
import re

pattern = r"hello"
text = "hello world"

match = re.match(pattern, text)
if match:
    print("Match found:", match.group())
else:
    print("No match")
  1. re.search() 예시
import re

pattern = r"world"
text = "hello world"

search = re.search(pattern, text)
if search:
    print("Search found:", search.group())
else:
    print("No match")
  1. re.findall() 예시
import re

pattern = r"\d+"  # 숫자 하나 이상
text = "There are 123 apples and 456 oranges."

findall = re.findall(pattern, text)
print("Findall results:", findall)
# 출력: Findall results: ['123', '456']
  1. re.sub() 예시
import re

pattern = r"apples"
replacement = "bananas"
text = "I like apples."

sub = re.sub(pattern, replacement, text)
print("Sub result:", sub)
# 출력: Sub result: I like bananas.

5. 고급 패턴 예시

  1. 이메일 주소 찾기
import re

pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
text = "Please contact us at support@example.com for further information."

emails = re.findall(pattern, text)
print("Emails found:", emails)
# 출력: Emails found: ['support@example.com']
  1. 전화번호 찾기
import re

pattern = r"\b\d{3}[-.]?\d{3}[-.]?\d{4}\b"
text = "Call me at 123-456-7890 or 987.654.3210."

phone_numbers = re.findall(pattern, text)
print("Phone numbers found:", phone_numbers)
# 출력: Phone numbers found: ['123-456-7890', '987.654.3210']

결론

정규표현식은 문자열을 다루는 데 매우 유용한 도구입니다. 파이썬의 re 모듈을 사용하면 다양한 패턴을 정의하고, 문자열에서 원하는 정보를 쉽게 추출하거나 대체할 수 있습니다.

반응형