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

Word Boundary — \b

~8 min · word-boundary, anchors, zero-width

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

Word 와 비-word 사이 invisible 위치

\b 는 word 글자 (\w) 와 비-word 글자 사이 경계 매칭하는 zero-width assertion. 소비 안 하고 "이 위치가 word boundary" 라고 주장만.

\bcat\bThe cat sat 의 단어 cat 매칭, concatenatecat 안 매칭. concatenate 에선 c 앞에 다른 word 글자 (boundary 없음), t 뒤에도 다른 word 글자 (boundary 없음).

Boundary 발생 위치

\b 매칭 위치:

  • 문자열 시작, 첫 글자가 word 글자면.
  • 문자열 끝, 마지막 글자가 word 글자면.
  • word 와 비-word 글자 사이 (어느 순서든).

\B 는 inverse — "word boundary 가 아님." 단어 *안에서* 만 매칭에 유용: \Bcat\Bconcatenatecat 매칭, The cat sat 의 안 함.

다시 Unicode 주의

Word boundary 는 \w 정의 의존, 그건 flavor + 플래그에 따라 다름. ASCII-only 모드면 \b 가 한글 텍스트를 단어로 인식 안 함, 안녕 에 ASCII 모드의 \w 글자 없으니까. Unicode 모드 (Python 기본; JS 의 u 플래그) 로 전환하면 동작.

Code

Word boundary 실전·python
import re

# 단어 단위 매칭
re.findall(r'\bcat\b', 'The cat sat in concatenate')
# ['cat']  — 'concatenate' 안의 'cat' 제외

# 'p' 로 시작하는 모든 단어
re.findall(r'\bp\w+', 'pippa loves python and pasta')
# ['pippa', 'python', 'pasta']

# \B 로 단어 안만
re.findall(r'\Bing\b', 'singing rings stings')
# ['ing', 'ing']  — suffix 만 사용, standalone 'ing' 안 함

External links

Exercise

한국어+영어 혼합 텍스트에서 단어 cat 과 단어 Pippa 검색. \bcat\b 가 영어 동작하고, \bPippa\b 가 어느 언어가 둘러싸도 동작 확인. 그 다음 한국어 단어 \b피파\b — 동작? 어느 flavor? 어느 플래그?

Progress

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

댓글 0

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

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