Python

정규표현식(3) [Python]

JEO96 2022. 11. 28. 19:59
반응형

 

 

반복 패턴 검사하기

다음은 반복 단어를 찾는 검색 패턴이다.

(\w+) \1

이 패턴은 w 문자(글자, 숫자 혹은 언더스코어) 중 1개 이상으로 나열된 단어와 일치한 후 빈칸 다음에 동일한 단어가 반복되는 것을 찾는다.

이 패턴은 다음 문장과는 일치하지 않는다.

the dog

the와 dog는 모두 단어 조건(\w+)에 부합되지만, 두 번째 단어가 첫 번째 단어와 동일하지 않다.

단어 the는 태그되었지만, 이 경우에는 반복되지 않았다.

반면 다음 문장은 이 패턴과 일치한다. 태그된 부분 문자열인 the가 반복되기 때문이다.

the the

동일 패턴을 사용한 전체 코드를 살펴보자. 대상 문자열을 the the로 설정했다.

import re

s = 'The cow jumped over the the moon.'
m = re.search(r'(\w+) \1', s)
print(m.group(), '...found at', m.span())

# 출력
# the the ...found at (20, 27)

텍스트 교체하기

re.sub(검색_패턴, 교체_문자열, 대상_문자열, count=0, flags=0)

 

import re
s = 'Get me a new dog to befriend my dog.'
s2 = re.sub('dog', 'cat', s)
print(s2)

# 출력
# Get me a new cat to befriend my cat.
import re

s = 'The the cow jumped over over the moon.'
s2 = re.sub(r'(\w+) \1', r'\1', s, flags=re.I)
print(s2)

#  The cow jumped over the moon.
반응형

'Python' 카테고리의 다른 글

정규표현식(2) [Python]  (0) 2022.11.17
정규표현식(1) [Python]  (0) 2022.11.16
리스트 복사 vs 리스트 변수 복사, 얕은 복사 vs 깊은 복사  (0) 2022.11.15
str 불리언(is) 메서드[Python]  (0) 2022.11.11
set(세트)[Python]  (0) 2022.11.11