C.W.K.
Stream
Lesson 07 of 12 · published

Named 그룹 — (?P<name>...)

~8 min · named-groups, readability

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

번호 그룹은 fragile, named 그룹은 안정

패턴이 자라면 그룹 번호가 괄호 추가/제거 마다 바뀜. Named 그룹이 각 캡처에 번호 대신 참조하는 이름 줘서 해결.

문법은 flavor 마다:

  • Python / 옛 PCRE: (?P<name>...)
  • .NET / PCRE / JavaScript: (?<name>...)
  • Named 그룹 backreference (Python): (?P=name)
  • Named 그룹 backreference (.NET / PCRE): \k<name>

Python 은 둘 다 지원: (?P<name>...) (자기 거) 와 3.x 부터 (?<name>...). 언어 간엔 가능하면 bare 꺽쇠 형태 선호.

Named 그룹 사용 이유

이유 셋:

  1. 가독 호출자. m.group('year') 가 self-documenting; m.group(1) 은 주석 필요.
  2. 편집 가로질러 안정. 중간에 그룹 추가해도 m.group('year') 안 깨짐.
  3. Self-documenting 패턴. 미래의 자신이 (?P<email>...) 읽고 뭐 캡처되는지 앎.

비용

언급할 만한 거 없음. Named 그룹 무료. 그룹 목적이 위치로부터 명백하지 않을 때마다 사용.

Code

Named 그룹·python
import re

# Python 스타일
pattern = r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})'
m = re.match(pattern, '2026-05-04')
print(m.group('year'))   # '2026'
print(m.group('month'))  # '05'
print(m.groupdict())     # {'year': '2026', 'month': '05', 'day': '04'}

# 언어 간 꺽쇠 형태 (Python 3.x 에서도 동작)
pattern = r'(?<year>\d{4})-(?<month>\d{2})'

# 이름으로 backreference
re.findall(r'(?P<word>\w+)\s+(?P=word)', 'the the cat sat sat')
# ['the', 'sat']

# Self-documenting 검증기
USER = re.compile(r'''
    ^
    (?P<localpart>[\w.+-]+)
    @
    (?P<domain>[\w-]+\.[\w.-]+)
    $
''', re.VERBOSE)
m = USER.match('hi@pippa.dev')
print(m.group('localpart'))  # 'hi'
print(m.group('domain'))     # 'pippa.dev'

External links

Exercise

본인이 작성한 2-3 그룹 패턴을 named 그룹으로 다시 작성. 이걸 쓰는 매칭 코드가 self-documenting 되어야 (예: m.group(1) 대신 m.group('year')).

Progress

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

댓글 0

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

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