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

Python re 모듈 기초

~10 min · python, re-module

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

Python에서는 다섯 함수부터 익히면 돼

내장 re 모듈의 검색 함수는 어디서 시작하고 몇 개를 돌려주는지에 따라 나뉘어.

  • re.search(pattern, text)는 문자열 어디서든 첫 매칭을 찾아 일치 객체를 돌려줘.
  • re.match(pattern, text)는 문자열 시작 위치에서만 첫 매칭을 시도해.
  • re.fullmatch(pattern, text)는 문자열 전체가 패턴과 맞을 때만 성공해.
  • re.findall(pattern, text)은 서로 겹치지 않는 결과를 목록으로 모아 줘.
  • re.finditer(pattern, text)는 각 일치 객체를 차례로 내놓는 반복자를 돌려줘.

앞의 세 함수는 실패하면 None을 반환해. 여러 결과의 위치나 그룹까지 살펴봐야 한다면 findall보다 finditer가 다루기 편해.

일치 객체에서 값과 위치를 꺼내

  • m.group()m.group(0)은 전체 매칭을 돌려주고
  • m.group(N)m.group('name')은 번호나 이름으로 캡처 값을 꺼내고
  • m.groups()m.groupdict()은 여러 캡처를 튜플이나 딕셔너리로 모아 주고
  • m.start(), m.end(), m.span()은 매칭한 범위의 위치를 알려 줘.

포함, 시작, 전체를 구분해

re.match(r'world', 'hello world')world가 문자열 중간에 있어서 실패해. 어디에 포함됐는지 찾으려면 search, 시작에서만 보려면 match, 입력 전체를 검증하려면 fullmatch를 골라.

Code

Python re 기본·python
import re

text = 'order #1138 placed on 2026-05-04'

# search — 어디든 찾기
m = re.search(r'#(\d+)', text)
m.group()      # '#1138'
m.group(1)     # '1138'

# match — 시작만
re.match(r'order', text)  # Match
re.match(r'placed', text)  # None

# fullmatch — 전체
re.fullmatch(r'\d{4}', '2026')         # Match
re.fullmatch(r'\d{4}', '2026 today')   # None

# findall — 매칭 리스트
re.findall(r'\d+', text)
# ['1138', '2026', '05', '04']

# finditer — Match 객체 iterator
for m in re.finditer(r'(\w+)=(\d+)', 'a=1 b=2 c=3'):
    print(m.group(1), '→', m.group(2))
# a → 1
# b → 2
# c → 3

External links

Exercise

텍스트 파일 하나를 골라 같은 패턴을 re.search, re.findall, re.fullmatch에 각각 적용해. 첫 일치 객체, 전체 결과 목록, 전체 문자열 일치 객체 또는 None처럼 반환 모양이 어떻게 달라지는지 기록해.

Progress

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

댓글 0

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

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