Word boundaries

Beginner · 6 min

\b matches the position between a word character and a non-word character. Match whole words, see why café and C++ break it, and what grep and sed accept.

Before thisShorthand classesAnchors and line boundaries

Codeimas · 115 min · from 52:41

Word boundaries

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CodeimasReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • \b is a zero-width position: it sits where a \w character meets a \W character or the edge of the text. \B is every position that is not a boundary.
  • /\bcat\b/ finds the whole word cat, including inside cat-dog. It skips category, bobcat, concat and cat_1.
  • Boundaries are defined by \w. In JavaScript é is not a word character, so /\bcafé\b/ fails on 'café'. Python 3 counts é as a word character and succeeds.
  • \b between two non-word characters does not exist. /\bC\+\+\b/ fails on 'C++ rocks' but matches 'C++x'.
  • grep -w, \b in BSD grep, \< and \> in BSD grep and [[:<:]] in grep and sed all select whole words, but BSD sed -E ignores \b.

Cat, category and concatenate

You want to replace the word cat with dog in a sentence. The obvious pattern is /cat/g:

"the cat concatenates the cat".replace(/cat/g, "dog")
// "the dog condogenates the dog"

It rewrote concatenates too. The pattern has no idea where words begin and end, so cat inside any word is a match. What you want to say is “cat, as a whole word”. That needs a way to talk about the edge of a word, and the word boundary \b is that.

"the cat concatenates the cat".replace(/\bcat\b/g, "dog")
// "the dog concatenates the dog"

A boundary is a position

\b is a zero-width position, like ^ and $ in the previous lesson. It matches a place between two characters when one of them is a word character (\w, so letters, digits and _) and the other is not, or when the text starts or ends with a word character. You can make the positions visible by inserting a bar at each one:

"cat dog".replace(/\b/g, "|")         // "|cat| |dog|"
"  cat, dog!".replace(/\b/g, "|")     // "  |cat|, |dog|!"
"cat dog".replace(/\B/g, "-")         // "c-a-t d-o-g"

The first line has four boundaries: the start of cat, its end, and the same for dog. The \B is the opposite, every position that is not a boundary, which is why the dashes land inside the words. The spaces and punctuation got no bars because there is no word character on either side of a gap between two of them.

Now the cat test against eight strings, \bcat\b first and plain cat second:

"cat"        true  true
"category"   false true
"a cat sat"  true  true
"cat-dog"    true  true
"bobcat"     false true
"concat"     false true
"cat_1"      false true
"Cat"        false false

A hyphen is not a word character, so cat-dog counts as containing the whole word cat. An underscore is one, so cat_1 does not. And Cat fails both, because matching is case-sensitive. The \B can also anchor in the middle of a word: /\Bcat/.test("bobcat") and /cat\B/.test("category") were both true.

Digits count as word characters

A boundary counts digits as part of a word, so a number glued to letters has no boundary inside it:

"id42".match(/\b\d+/)       // null
"42abc".match(/\b\d+\b/)    // null
"a42".match(/\B\d+/)        // [ '42', index: 1 ]

Where \b surprises you

Because \b is built on \w, it inherits every limit from the shorthand classes lesson. In JavaScript é is not a word character:

/\bcafé\b/.test("café au lait")   // false
/\bcafé\b/.test("café")           // false
/\bcaf\b/.test("café")            // true

The third line is the bug: there is a boundary between f (word) and é (not a word character), so \bcaf\b thinks it found a whole word caf inside café. Python 3 gets it the other way round, because its \w is Unicode-aware: re.search(r"\bcafé\b", "café") found a match, and with re.A it did not, while \bcaf\b matched only with re.A. For text beyond ASCII you will need a different approach, such as lookaround with Unicode property escapes. Later lessons cover that.

The second surprise is symbols. A boundary needs a word character on one side:

/\bC\+\+\b/.test("C++ rocks")   // false
/\bC\+\+\b/.test("C++x")        // true
/\bC\+\+(?!\w)/.test("C++ rocks") // true

After ++ comes a space, and a plus and a space are both non-word characters, so there is no boundary. In C++x the x is a word character, so there is one. The reverse of what you wanted. The last line replaces the trailing \b with a negative lookahead, which says “not followed by a word character”. It is previewed here and has its own lesson later.

In the command line tools

For whole words in grep you have several options. On this machine, with BSD grep, each of these printed cat, the cat sat and cat-dog, and skipped category and bobcat: grep -w cat, grep -E '\bcat\b', grep '\<cat\>' and grep '[[:<:]]cat[[:>:]]'. pcre2grep -o '\bcat\b' found three, and perl found cat once in cat-dog bobcat.

sed is less forgiving. BSD sed -E 's/\bcat\b/X/g' and sed 's/\<cat\>/X/g' both left cat concat unchanged, and only sed -E 's/[[:<:]]cat[[:>:]]/X/g' worked, printing X concat. The shell side is covered by searching with grep.

About the video

The embed is a clip of Codeimas’s “Complete Regex Course for Beginners (2 Hours)”, published on 2 August 2026 and 1 hour 54 minutes 52 seconds long. It plays the chapter “Word Boundaries”, from 52:41 to 58:45 of the description’s list, about six minutes in a JavaScript course. I couldn’t read a transcript, so I can’t say how it treats non-ASCII text or symbols. The channel has a small audience, so there is little outside signal on its accuracy, and a reader should be ready to skip this clip if it goes wrong. English per its title and description.

What I did not run

GNU grep, regex101, and \b with the u and i flags together. I also did not run Python’s \b with Unicode categories beyond é.

Next

That finishes the characters and the positions. The next group deals with how many times a piece may repeat, starting with the three most common quantifiers: Quantifiers: star, plus and question.

Check yourself

  1. 01Which of 'cat', 'category', 'bobcat' and 'cat-dog' does /\bcat\b/ match, and why?

    cat and cat-dog. In both, the letters sit between non-word characters or text edges. In category and bobcat a word character touches the cat on one side, so there is no boundary.

  2. 02What does 'cat dog'.replace(/\b/g, '|') return?

    '|cat| |dog|'. A boundary is a position, so the replacement inserts a bar at each of the four spots without removing anything.

  3. 03Why does /\bcafé\b/.test('café') return false in JavaScript?

    \b depends on \w, and JavaScript's \w is ASCII only. é is a non-word character, so the end of the string after it is a non-word to non-word edge, which is not a boundary.

  4. 04How would you replace the standalone word cat with dog but leave 'concatenates' alone?

    Use 'the cat concatenates'.replace(/\bcat\b/g, 'dog'). Without the boundaries the replacement turns concatenates into condogenates.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark