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) 가 모든 비-overlapping 매칭을 replacement 로 치환.

치환 가능:

  • 리터럴 문자열: re.sub(r'\d+', 'NUM', 'a 1 b 22 c 333')'a NUM b NUM c NUM'
  • Backreference 있는 패턴: group 1 은 r'\1', named 그룹은 r'\g<name>', 전체 매칭은 r'\g<0>'.
  • Callable: Match 객체 받고 문자열 반환. 동적 로직에 가장 강력.

count 파라미터

re.sub(pattern, replacement, text, count=N) 가 첫 N 매칭만 치환. "첫 등장만 수정" 또는 "X 개 이상 처리 안 함" 에 유용.

re.subn — 카운트 받기

re.subn 이 튜플 (new_string, num_replacements) 반환. 뭔가 변했는지 알아야 할 때 유용.

re.split — 정규식 구분자로 split

re.split(pattern, text)str.split 같지만 구분자가 어떤 정규식이든. 모든 매칭에서 split.

패턴에 캡처 그룹 있으면 캡처된 텍스트가 결과 리스트에 INCLUDED. re.split(r'(\W+)', 'hello, world')['hello', ', ', 'world'] 반환 — 구분자 보존.

Code

치환과 split·python
import re

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

# 치환에 backreference
re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', '2026-05-04')
# '05/04/2026'

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

# Callable 치환 — 풀 programmatic 통제
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)

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

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

External links

Exercise

Callable 있는 re.sub 사용해서 문자열의 모든 숫자를 영어 단어로: '5' → 'five', '10' → 'ten'. Callable 안에서 dict 룩업. 'I have 3 cats and 7 dogs' 테스트.

Progress

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

댓글 0

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

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