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

특수 글자 escape — 언제, 어떻게

~8 min · escaping, metacharacters, raw-strings

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

백슬래시는 특수를 리터럴로, 그 반대도

두 가지 사실:

  1. 메타문자를 리터럴로 매칭하려면 앞에 백슬래시: \. 는 점 매칭, \$ 는 달러 기호 매칭, \\ 는 백슬래시 매칭.
  2. 평범한 문자에서 특수 의미 만들려면 앞에 백슬래시: \d 는 숫자, \b 는 word boundary, \n 은 줄바꿈.

백슬래시는 universal mode flip.

Raw string 이 정신 보호

Python, JavaScript 템플릿 리터럴, 대부분 언어에서 백슬래시는 또 string-escape 글자야. 그래서 Python string 안의 "\d" 는 정규식이 보기 전에 string parser 가 해석 — 어떤 땐 무해, 어떤 땐 catastrophic.

정규식 패턴엔 항상 raw string (또는 등가물) 사용. Python: r"\d+". Rust: r"\d+". JavaScript regex literal: /\d+/ (슬래시가 같은 보호 제공).

Raw string 없으면: Python 의 "\d" 는 우연히 "\\d" 와 같지만 "\b" 는 ASCII bell 글자 (8) — 패턴이 조용히 잘못됨.

Programmatic escape

사용자 입력이나 변수에서 정규식 빌드한다면 escape 함수 사용: Python re.escape(), JavaScript 는 polyfill 필요 (built-in 없음), Go regexp.QuoteMeta(). 절대로 raw 사용자 입력을 패턴에 concat 하지 마.

Code

Escape 제대로·python
import re

# 리터럴 $19.99 매칭
re.findall(r'\$\d+\.\d{2}', 'price was $19.99 today')
# ['$19.99']

# Raw string 없이 — 조용히 잘못됨
import re
pattern = "\d+"  # Python 이 봄: "\d+" → str 이 백슬래시 해석
print(repr(pattern))  # 실제 '\\d+'  (버전 의존)

# 사용자 입력 programmatic escape
user_input = 'price: $19.99'
safe = re.escape(user_input)
print(safe)
# 'price:\\ \\$19\\.99'
re.findall(safe, 'note: price: $19.99 today')

External links

Exercise

https://example.com/path?query=1 같은 URL 을 *리터럴* 로 매칭하는 정규식 빌드 — 모든 특수 글자 정확히 escape. 그 다음 같은 URL string 에 re.escape() 사용해서 손으로 한 escape 와 함수 결과 비교.

Progress

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

댓글 0

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

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