본문 바로가기

언어/Python

[ 파이썬 / Python ] re 객체를 이용해서 문자열 검색, 교체하기

반응형

Python의 re 모듈은 정규 표현식을 사용하여 문자열을 검색하고 교체할 수 있는 강력한 도구를 제공합니다.

1. re 모듈 사용하기

먼저 re 모듈을 import 해야 합니다.

import re

2. re.search()

이 함수는 문자열 내에서 패턴을 검색하고, 매치 객체를 반환합니다. 패턴을 찾지 못하면 None을 반환합니다.

import re

s = "Hello, world!"
match = re.search(r"world", s)

if match:
    print(f"Found '{match.group()}' at position {match.start()}")
else:
    print("Not found")

3. re.findall()

이 함수는 문자열 내에서 패턴과 일치하는 모든 부분 문자열을 리스트로 반환합니다.

import re

s = "The rain in Spain"
matches = re.findall(r"\b\w+ain\b", s)
print(matches)  # 출력: ['rain', 'Spain']

4. re.finditer()

이 함수는 문자열 내에서 패턴과 일치하는 모든 부분 문자열을 반복 가능한 객체로 반환하며, 각 요소는 매치 객체입니다.

import re

s = "The rain in Spain"
matches = re.finditer(r"\b\w+ain\b", s)
for match in matches:
    print(f"Found '{match.group()}' at position {match.start()}")

5. re.sub()

이 함수는 패턴과 일치하는 부분 문자열을 다른 문자열로 교체합니다.

import re

s = "Hello, world! Welcome to the world of Python."
new_s = re.sub(r"world", "universe", s)
print(new_s)  # 출력: "Hello, universe! Welcome to the universe of Python."

6. re.subn()

이 함수는 re.sub()와 동일하게 동작하지만, 교체된 횟수도 함께 반환합니다.

import re

s = "Hello, world! Welcome to the world of Python."
new_s, num_replacements = re.subn(r"world", "universe", s)
print(new_s)            # 출력: "Hello, universe! Welcome to the universe of Python."
print(num_replacements) # 출력: 2

7. 예제: 이메일 주소 찾기

정규 표현식을 사용하여 이메일 주소를 찾는 예제입니다.

import re

text = "Please contact us at support@example.com for further information."

email_pattern = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"
match = re.search(email_pattern, text)

if match:
    print(f"Found email: {match.group()}")
else:
    print("No email found")

8. 예제: 전화번호 형식 변환

정규 표현식을 사용하여 전화번호 형식을 변환하는 예제입니다.

import re

phone_number = "123-456-7890"
new_phone_number = re.sub(r"(\d{3})-(\d{3})-(\d{4})", r"(\1) \2-\3", phone_number)
print(new_phone_number)  # 출력: "(123) 456-7890"
반응형