Word boundary regex: what \b matches, where it fails, and when to use something else
A practical review of the regex word boundary \b: what it matches, how it handles apostrophes, Unicode and non-Latin scripts, engine differences, and tokenization limits.
A word boundary in a regular expression, usually written \b, is a common regex token and a frequently misunderstood one. It looks like a character but matches a position. This review covers what it does, where it is reliable for whole-word matching and tokenization, and where it fails without any error. That last part matters most for non-English text, which is relevant to readers who come to the topic as 'границы слов в регулярных выражениях'.
Short verdict
\b works well for whole-word search and replace when the words you care about fit the engine's definition of a word character. That usually means English or other Latin-script text without unusual punctuation, in an engine whose Unicode behavior you have checked. Its main benefit is that it is concise and zero-width: it anchors a match without consuming characters. The decisive tradeoff is that a 'word' is defined by \w (letters, digits and underscore, sometimes ASCII only), not by any language's rules. That makes \b a poor general-purpose tokenizer for multilingual text, contractions, hyphenated compounds, or scripts written without spaces.
In some cases a simpler or different tool is better. If you only need to split on spaces, a plain string split is clearer and easier to maintain. If you need linguistically sensible tokens across languages, use Unicode text segmentation (the word-boundary rules in Unicode Standard Annex #29) through a library, or use a dedicated tokenizer.
What \b actually matches
\b matches a position where a word character is on one side and a non-word character, or the start or end of the input, is on the other. \B matches every position where \b does not.
- Before the first character, if that character is a word character.
- After the last character, if that character is a word character.
- Between two adjacent characters, when exactly one of them is a word character.
Because \b is zero-width, it transforms nothing. Text tools that reverse, mirror or restyle characters change the stored characters or their appearance. A boundary assertion only decides which spans of the original text count as a match. In a search-and-replace, only the matched spans are rewritten, and the boundary itself never adds or removes a character.
Pattern: \bcat\b
Text: cat concatenate cat's bobcat
Applying the definition to this example gives two matches: the standalone 'cat' and the 'cat' in 'cat's', because the apostrophe is a non-word character. 'concatenate' and 'bobcat' do not match, because the letters around 'cat' there are word characters, so there is no boundary. These results follow from the definition and are not reported test output.
Where a regex 'word' stops matching real words
- Apostrophes: \b\w+\b applied to 'don't' yields 'don' and 't', because the apostrophe creates two boundaries.
- Hyphens: 'e-mail' and 'well-known' become two tokens each.
- Digits and underscores count as word characters: 'snake_case_name' and 'item42' are single words, which suits code but often not prose.
- Tokens that start or end with punctuation: \bC++\b does not match 'C++' followed by a space or the end of the text, because there is no boundary between two non-word characters. \b.NET fails for the same reason.
- Inside a character class: in many engines [\b] means the backspace character, not a boundary.
Unicode, accents and non-Latin scripts
Whether Cyrillic, Greek or accented Latin letters count as word characters depends on the engine and its flags. In an ASCII-only mode, every Cyrillic letter is a non-word character. As a result, \bслово\b fails on 'слово' surrounded by spaces, since both sides of each intended boundary are non-word characters. Meanwhile, boundaries do appear wherever Latin and Cyrillic letters meet. The pattern then either finds nothing or splits mixed-script text in unexpected places.
Combining marks are a further risk. A decomposed 'é' is stored as 'e' followed by a combining acute accent. Unicode's regex guidelines recommend that \w include combining marks, but implementations differ. In an engine where \w excludes them, a boundary can fall inside what a reader sees as one letter. Normalizing text to NFC first reduces the problem but does not remove it, because some letter-plus-mark combinations have no precomposed form. Emoji, including multi-code-point sequences joined with zero-width joiners, are non-word characters throughout. So \b never splits an emoji, but it never treats one as a token either.
Scripts usually written without spaces between words, such as Chinese, Japanese and Thai, get no useful word segmentation from \b. Boundaries appear only where the script meets punctuation, spaces or other scripts. Splitting these languages into words requires dictionary- or model-based segmentation.
Engine differences to check before reusing a pattern
| Engine | Word-boundary syntax | Default notion of word characters |
| JavaScript | \b, \B | ASCII-based; the u flag does not extend \w or \b to Cyrillic or accented letters |
| Python 3 (re) | \b, \B | Unicode-aware for str patterns; re.ASCII restricts it; bytes patterns are ASCII |
| .NET | \b, \B | Unicode-aware; RegexOptions.ECMAScript restricts it to ASCII |
| Java | \b, \B | Depends on version and flags; UNICODE_CHARACTER_CLASS enables Unicode word characters; check the documentation for your JDK |
| PCRE-based tools | \b, \B | ASCII by default; Unicode word characters need UTF and UCP options, which wrappers expose differently |
| PostgreSQL | \y (boundary), \m (word start), \M (word end) | \b means backspace, not a boundary |
| GNU grep | \b, <, >, and the -w option | Word characters follow the current locale |
| MySQL | \b in 8.0 and later (ICU-based); [[:<:]] and [[:>:]] in earlier versions | Depends on version |
This table summarizes commonly documented defaults. It is not based on tests run for this article. Engines change between releases, so confirm the behavior in the documentation for the exact version you deploy.
In engines that support Unicode property escapes and lookbehind, you can define the boundary yourself instead of relying on \b. The JavaScript pattern below treats letters, combining marks, digits and underscore as word characters in any script.
const wholeWord = /(?<![\p{L}\p{M}\p{N}_])слово(?![\p{L}\p{M}\p{N}_])/u;
Some engines also offer boundaries based on the Unicode segmentation rules directly. Perl has \b{wb}, and ICU's regex engine has a flag that switches \b to Unicode word-boundary rules. Check that these are available in your version before depending on them.
Will the pattern survive copying and sharing?
Matching with \b leaves the text itself unchanged, so its readability, searchability and screen-reader behavior are unaffected. The accessibility concerns that apply to styled or mirrored text do not arise here. The portability risks lie in the pattern itself.
- String escaping: in a normal string literal in Python, Java, JavaScript or C#, \b is the backspace character. Use a raw string in Python (r"\bword\b"), a verbatim string in C# (@"\bword\b"), or a doubled backslash ("\bword\b") in Java and in JavaScript's RegExp constructor. A JavaScript regex literal such as /\bword\b/ needs no doubling.
- JSON and configuration files: the backslash must be escaped again, so check what the consuming program actually receives.
- Switching engines: the same characters can mean something else. In PostgreSQL, \b is a backspace, and \w can shrink from Unicode to ASCII when a pattern moves from Python to JavaScript.
- Editor and spreadsheet search dialogs: regex dialects vary, and some do not support \b at all, so test before running a bulk replace.
Using word boundaries for tokenization: practical guidance
- Decide what counts as a token before writing a pattern: contractions, hyphenated compounds, numbers with separators, identifiers.
- Test with real samples that include apostrophes (both straight and curly), hyphens, digits, accented letters, decomposed characters and any non-Latin scripts you expect.
- Normalize text, usually to NFC, before matching.
- When a token has a definable shape, match the tokens themselves rather than relying on boundaries between them; the explicit pattern below is easier to audit.
- For multilingual or unspaced text, use a Unicode segmentation library or a language-specific tokenizer instead of regex boundaries.
const tokens = text.match(/[\p{L}\p{M}\p{N}]+(?:['’-][\p{L}\p{M}\p{N}]+)*/gu) ?? [];
Evidence and gaps
No test results, benchmarks or engine-specific measurements were provided for this review. The explanations rest on the general definition of \b and on commonly documented engine defaults. The examples show outcomes derived from that definition, not observed output. Performance, behavior in specific applications, and version-by-version changes were not verified. Run your patterns against your own samples on the exact engine and version you plan to use.