본문 바로가기
내가 마주친 에러

정규표현식 sub 이용할때 주의할 점

by 나는 라미 2024. 11. 13.
728x90
반응형

re.search로 찾은 문자열을 그대로 re.sub를 이용해서 삭제하고 싶었다.

parentheses = re.search('\([\w|\W]*:[\w|\W]*\)', words)
if parentheses:
	words = re.sub(f"\({parentheses.group()}\)", '', words)

 

re.error: missing ), unterminated subpattern at position 2

 

re.search안에서 escape 문자가 포함된 경우 에러가 난다.

난 찾아낸 문자열 그대로를 삭제하고 싶기 때문에, 이를 escape 처리하는 문구를 넣어 주자.

 

parentheses = re.search('\([\w|\W]*:[\w|\W]*\)', words)
if parentheses:
	words = re.sub(re.escape(parentheses.group()), '', words)

 

728x90
반응형

댓글