본문 바로가기
C.W.K.
Stream
Lesson 02 of 10 · published

Python re.sub()와 re.split()

~10 min · python, substitution, split

Level 0패턴 호기심
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

치환은 정규식의 또 다른 절반이야

re.sub(pattern, replacement, text)는 서로 겹치지 않는 매칭을 모두 replacement로 바꿔.

치환값에는 다음 세 가지를 사용할 수 있어.

  • 리터럴 문자열: re.sub(r'\d+', 'NUM', 'a 1 b 22 c 333')'a NUM b NUM c NUM'
  • 역참조가 든 치환 문자열: 그룹 1은 r'\1', 이름 붙은 그룹은 r'\g<name>', 전체 매칭은 r'\g<0>'으로 참조해.
  • 콜백 함수: 일치 객체를 받아 새 문자열을 반환해. 조회나 조건 분기처럼 동적인 로직에 알맞아.

count 매개변수

re.sub(pattern, replacement, text, count=N)은 앞에서부터 최대 N개만 치환해. 첫 번째 등장만 고치거나 치환 횟수에 상한을 둘 때 유용해.

re.subn으로 치환 횟수도 받기

re.subn(new_string, num_replacements) 튜플을 반환해. 실제로 내용이 바뀌었는지 함께 확인할 수 있어.

정규식 구분자로 나누는 re.split

re.split(pattern, text)str.split과 비슷하지만 구분자 자리에 정규식을 받아. 패턴이 매칭된 위치마다 문자열을 나눠.

패턴에 캡처 그룹이 있으면 구분자로 잡힌 텍스트도 결과 목록에 들어가. 예를 들어 re.split(r'(\W+)', 'hello, world')는 구분자를 보존한 ['hello', ', ', 'world']를 반환해.

Code

치환과 분할·python
import re

# 단순 치환
re.sub(r'\d+', 'NUM', 'a 1 b 22 c 333')
# 'a NUM b NUM c NUM'

# 치환 문자열에서 역참조 사용
re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', '2026-05-04')
# '05/04/2026'

# 이름 붙은 그룹 참조
re.sub(r'(?P<year>\d{4})', r'[\g<year>]', 'born 1989, today 2026')
# 'born [1989], today [2026]'

# 콜백 함수로 치환 결과를 결정
def bracket_if_large(m):
    n = int(m.group())
    return f'[{n}]' if n > 100 else str(n)

re.sub(r'\d+', bracket_if_large, 'small 5 medium 50 large 500')
# 'small 5 medium 50 large [500]'

# subn은 치환 횟수도 반환
re.subn(r'\d+', 'NUM', 'a 1 b 2')
# ('a NUM b NUM', 2)

# 정규식 구분자로 분할
re.split(r'\W+', 'hello, world! how are you?')
# ['hello', 'world', 'how', 'are', 'you', '']

# 구분자를 보존하며 분할
re.split(r'(\W+)', 'hello, world')
# ['hello', ', ', 'world']

External links

Exercise

콜백 함수를 넘긴 re.sub로 문자열 안의 숫자를 영어 단어로 바꿔 봐. 예를 들어 '5''five', '10''ten'으로 치환해. 콜백 안에서 사전을 조회하고 'I have 3 cats and 7 dogs'로 테스트해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.