파이썬에서 단순한 str.replace() 메서드로는 처리하기 어려운 복잡한 패턴의 문자열을 치환해야 할 때가 있습니다. 이럴 때 re 모듈의 re.sub() 함수를 사용하면 정규식 패턴에 일치하는 모든 문자열을 원하는 값으로 손쉽게 교체할 수 있습니다.
re.sub() 기본 문법
re.sub(pattern, replacement, string) 형태로 사용하며, 문자열 전체에서 정규식 pattern과 일치하는 부분을 모두 찾아 replacement로 바꿔줍니다.
예제 코드
다음 예제는 텍스트 안에 섞여 있는 <[숫자>, </[숫자> 형태의 태그를 모두 제거하는 코드입니다.
import re line = 'this is a text with<[2> in between</[3> and then there are instances ... where the<[43> number ranges from 0-99</[76>.\ and there are many other lines in the text files \ with<[7> such tags </[8>' line = re.sub(r"</?\[\d+>", "", line) print(line)
정규식 패턴 해석
</?: 여는 태그(<)와 선택적으로 닫는 슬래시(/)에 일치합니다.\[: 특수문자인 대괄호[를 이스케이프하여 리터럴 문자로 인식시킵니다.\d+: 한 자리 이상의 숫자(0~9)에 일치합니다.>: 태그를 닫는 꺾쇠 괄호에 일치합니다.
실행 결과
this is a text with in between and then there are instances ... where the number ranges from 0-99.and there are many other lines in the text files with such tags
정리
이처럼 re.sub()를 활용하면 고정된 문자열이 아닌 패턴 기반 치환이 가능해집니다. 숫자가 몇 자리든, 여는 태그든 닫는 태그든 하나의 정규식으로 일괄 처리할 수 있다는 점이 string.replace()와 가장 큰 차이입니다. 참고로 파이썬 3부터는 print가 함수이므로 print(line)처럼 괄호를 붙여 작성해야 합니다.