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

90% 사용할 네 함수

Python 내장 정규식은 re 모듈에 살아. 네 함수가 대부분 사용 케이스 커버:

  • re.search(pattern, text) — 텍스트 어디서든 첫 매칭. Match 객체 또는 None 반환.
  • re.match(pattern, text) — 텍스트 시작에서만 매칭. Match 또는 None.
  • re.fullmatch(pattern, text) — 텍스트 전체 매칭. Match 또는 None.
  • re.findall(pattern, text) — 모든 비-overlapping 매칭 리스트로.
  • re.finditer(pattern, text) — Match 객체 iterator (그룹 있을 때 findall 보다 선호).

Match 객체

패턴 매칭하면 Match 객체 받아, 핵심 메서드:

  • m.group() 또는 m.group(0) — 전체 매칭
  • m.group(N) — N번째 캡처 그룹
  • m.group('name') — named 캡처 그룹
  • m.groups() — 모든 번호 그룹 튜플
  • m.groupdict() — 모든 named 그룹 dict
  • m.start(), m.end(), m.span() — 매칭 위치

Match vs search — 가장 흔한 혼동

re.match 는 문자열 시작만 체크. re.match(r'world', 'hello world') 가 None 반환. "포함" 은 re.search. "시작" 은 re.match. "정확히" 는 re.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 (전체 검증). 각각 다른 모양 반환 — Match 객체, 문자열 리스트, Match-or-None.

Progress

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

댓글 0

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

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