How do word boundaries work when matching whole words with regex?
Quick answer
In regex, \b usually asserts a position where a word character meets a non-word character, or where a word character meets the start or end of the string. It consumes no text, and “word character” is defined by the regex engine—not ordinary language. Python’s default string patterns treat Unicode alphanumeric characters and underscores as word characters; JavaScript’s usual rules use ASCII letters, digits, and underscores. Check your engine and input before relying on whole-word matches.
The question, the details, the next step.
A practical checklist
Record the regex engine and flags you will use.
Write down which letters, digits, and separators should count as word characters for your task.
Test a plain separated word, a longer adjoining word, and an underscore-adjacent case.
Include accented or other non-ASCII letters if they can occur in your input.
Compare expected and observed matches before using the pattern on real text.
A few more useful answers
Does \b consume or include a space?
No. It asserts a position and consumes no character. A space may be next to that position, but it is not part of the boundary assertion.
Does \b always mean a natural-language word boundary?
No. It reflects the regex engine’s definition of word characters, which may differ from a linguistic definition or your application’s rules.
Sources
References used for this guide.
- [S1] Python 3.15.2 re — Regular expression operations docs.python.org · Checked
- [S2] JavaScript word-boundary assertion: \b and \B developer.mozilla.org · Checked
