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

Word Boundaries — \b

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

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

The invisible position between word and non-word

\b is a zero-width assertion that matches the boundary between a word character (\w) and a non-word character. It doesn't consume anything; it just asserts "this position is a word boundary."

\bcat\b matches the word cat in The cat sat, but NOT the cat in concatenate. Because in concatenate, c is preceded by another word character (so no boundary there) and t is followed by another word character (no boundary there either).

Where boundaries occur

A \b matches at:

  • The start of the string, if the first character is a word character.
  • The end of the string, if the last character is a word character.
  • Between a word and a non-word character (in either order).

\B is the inverse — "NOT a word boundary." Useful for matching only inside words: \Bcat\B matches cat in concatenate but not in The cat sat.

Unicode caveats again

Word boundaries depend on the definition of \w, which varies by flavor and flag. In ASCII-only mode, \b won't recognize Korean text as words because 안녕 has no \w characters in ASCII mode. Switch to Unicode mode (Python default; u flag in JS) and it works.

Code

Word boundaries in action·python
import re

# Whole-word match
re.findall(r'\bcat\b', 'The cat sat in concatenate')
# ['cat']  — the 'cat' inside 'concatenate' is excluded

# Find every word starting with 'p'
re.findall(r'\bp\w+', 'pippa loves python and pasta')
# ['pippa', 'python', 'pasta']

# \B for INSIDE words
re.findall(r'\Bing\b', 'singing rings stings')
# ['ing', 'ing']  — only the suffix uses, not standalone 'ing'

External links

Exercise

Search a Korean+English mixed text for the word cat and the word Pippa. Confirm \bcat\b works for English and that \bPippa\b works regardless of which language surrounds it. Then try a Korean word like \b피파\b — does it work? In which flavor? With which flag?

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.