Level 1: Foundations · Lesson 8 of 30
Word boundary \b
The \b anchor matches the edge of a word. It lets you find whole words like cat without matching the letters inside concat or cats.
A word boundary, written \b, is an anchor. Like ^ and $, it matches a position, not a character. That position is any place where a word character sits on one side and a non-word character, or the start or end of the text, sits on the other side. Word characters are the same as \w: letters, digits and underscore.
The most common use is whole-word search. The pattern cat matches inside concat and cats, but \bcat\b matches only cat as a complete word. In cat concat cats cat. it finds the first cat and the last one, because the full stop after the last one is not a word character, so there is a boundary there.
You do not always need boundaries on both sides. \bun\w* finds words that start with un, such as undo and unit, but not the un inside fun or sun. In the other direction, \w*ing\b finds words ending in ing, like sing and ringing, without matching the ing inside kingdom.
Boundaries are also great for numbers. \d\d on 12345 matches 12 and 34, which is rarely what you want. \b\d\d\b matches only standalone two-digit numbers. The same idea helps with codes: \bID\d+\b skips XID34 because there is no boundary between X and I.
There is an opposite anchor, \B, which matches any position that is not a word boundary. \Bcat\B would match the cat in the middle of concatenate but not a standalone cat. It is used less often but is good to recognise.
Be careful with non-ASCII text. In JavaScript, \w and therefore \b only understand ASCII letters by default, so a word like café has a boundary before the é. Python 3, C#, Rust and Go handle this differently, and some treat Unicode letters as word characters by default. If your text includes accented letters, test your pattern in the language you will use.
Also note that a hyphen is not a word character. So \bwell\b matches inside well-known. That is usually fine, but if you treat hyphenated words as single words, you may need a different approach, such as lookarounds or a custom set.
Live tester
2 matches (JavaScript engine)
cat concat cats cat.
Examples
Numbers
/\b\d\d\b/g7 42 1234 99
Matches: “42”, “99”
Only standalone two-digit numbers match; digits inside 1234 are skipped.
Text
/\bthe\b/gthe other theme, the end
Matches: “the”, “the”
The letters inside other and theme are ignored because there is no boundary around them.
Codes
/\bID\d+\b/gID12 XID34 ID56x ID78
Matches: “ID12”, “ID78”
XID34 has no boundary before I, and ID56x has no boundary after 6, so only ID12 and ID78 match.
Practice tasks
Your regex runs over the text with the global flag. It passes when it finds every required match and nothing that should be left out.
Task 1: Match whole words that start with un.
undo under fun sun unit
Task 2: Match standalone two-digit numbers only.
5 12 345 67 8901
Task 3: Match words that end in ing.
sing singer ringing kingdom