C.W.K.
Stream
Lesson 04 of 10 · published

Python Raw String — 왜 r'\d+'

~6 min · python, strings, escape

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

Double-escape 문제

Python 문자열에서 백슬래시 \ 가 escape 글자. '\n' 은 줄바꿈; '\t' 는 탭; '\b' 는 ASCII bell.

정규식 패턴에서도 백슬래시가 escape 글자. \d 는 숫자; \b 는 word boundary; \. 는 리터럴 점.

Raw string 없이는 정규식 digit class 위해 '\\d' 작성 — Python string parser 위해 한 백슬래시, 정규식 위해 다른 백슬래시. 짜증나고 에러 prone.

Raw string 이 Python 해석 비활성

문자열 리터럴에 r 접두: r'\d+'. 이제 Python 이 백슬래시 해석 안 함 — 정규식에 변경 없이 통과. r'\b\w+\b' 가 보이는 그대로 의미.

Raw string 없이 버그 종류

Python 의 '\b' 는 ASCII bell 글자 (chr(8)). re.search('\bword', text) 작성하면 Python 이 패턴을 '\x08word' 로 봄 — 의도한 거 절대 아님. 일부 패턴은 raw string 없이도 동작 ('\d' 가 유효한 Python escape 아니라 두 글자로 머묾) 하지만 의존하는 거 fragile.

Python 정규식 패턴엔 항상 raw string. 예외 없음.

동적 패턴엔 f-string

변수 interpolate 하려면 raw + f-string 결합: rf'\b{word}\b'. 또는 사용자 입력 interpolate 할 때 re.escape: rf'\b{re.escape(word)}\b'.

Code

Raw string 이 구원·python
import re

# Raw 없이 — Python 이 \b 를 bell 로 해석
bool(re.search('\bword', 'a word here'))   # False (아마 잘못!)
bool(re.search(r'\bword', 'a word here'))  # True

# Raw + f-string 으로 변수 interpolation
name = 'pippa'
pattern = rf'\b{name}\b'  # r'\bpippa\b'
bool(re.search(pattern, 'hi pippa'))  # True

# 신뢰 안 되는 입력 interpolate 할 때 escape
user_query = 'foo.bar'  # 사용자가 리터럴 문자열 입력
safe = re.escape(user_query)  # 'foo\\.bar'
pattern = rf'\b{safe}\b'
bool(re.search(pattern, 'we found foo.bar in the data'))  # True

# Raw string 이 홀수 백슬래시로 끝날 수 없음 — Python quirk
# r'\\' OK (백슬래시 2개)
# r'\' SyntaxError
# Workaround: '\\' (escape 됨) 또는 r'\\' 뒤 리터럴

External links

Exercise

Python 에서 print('\b')print(r'\b') 돌리기. 차이 인지. 이제 '\bcat\b' (r-접두 없이) 검색하는 작은 스크립트 작성, 'a cat sat' 에서 'cat' 못 찾는 이유 설명.

Progress

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

댓글 0

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

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