\b is the zero-width assertion that matches the position between a word character and a non-word character: the start of "cat" in "the cat" or the end of "cat" in "cat food", but not anywhere inside "scatter". \B is its negation, a position where there is no word boundary. Both are zero-width: they consume no characters, they only assert position.
What is a word boundary (\b) in regex?
A word boundary is the zero-width position between a word character (\w: a letter, digit, or underscore) and a non-word character (\W: anything else), or at a string edge adjacent to a word character. The \b metacharacter matches that position. It is a position, not a character: \b does not match a literal b, and it consumes nothing, so it never "uses up" any of the input.
In one line: \b says "a word starts or ends right here". The classic use is "match a whole word, not the substring inside another word": \bcat\b matches "cat" in "the cat sat" but not "cat" in "scatter" or "category". \B is the negation, every position that is not a word boundary.
That covers the short answer. The rest of this page is the full reference: the exact positions that match, per-engine support (JavaScript, Python, Java, PCRE, .NET, POSIX, Go, Rust), Unicode caveats, the lookaround alternative when you need finer control, and worked examples in Python and JavaScript. The same idea extends to log parsing (token-precise matches), refactor tools (rename only whole identifiers), and search-and-replace (don't mangle "Java" into "Python" inside "JavaScript").
Jump to:
\bis a boundary, not the letterb- Word characters: what counts as
\w - Where
\bmatches: the four positions - Negated word boundary:
\B - Engine compatibility
- Unicode word boundaries
- Lookaround alternative for finer control
- Common use cases with examples
- Common mistakes
- FAQ
\b is a boundary, not the letter b
This trips up a lot of people searching for "b in regex" or "regex b", so it is worth being explicit. The escape \b (backslash-b) is a word boundary, a zero-width position. It is not the literal character b. To match an actual lowercase b you just write b with no backslash. So:
bmatches the letter b.\bmatches a position (a word boundary), and matches no character at all.\bb\bmatches a standalone single-letter word "b" (the boundary, then the letter, then the boundary).
There is one more wrinkle that catches people out: inside a character class, \b changes meaning. In most engines [\b] is the backspace control character (U+0008), not a word boundary. A word boundary is meaningless inside a [...] class, so the engine reuses the escape for backspace there, the same way it does in string literals. If you meant "word boundary", keep \b outside the brackets.
import re
re.findall(r"\bb\b", "a b c bb") # ['b'] - the standalone "b", not the "bb"
re.search(r"[\b]", "a\bc") # match - [\b] is backspace inside a classWhat does \w mean in regex?
\w matches a single word character: a letter, a digit, or an underscore. In JavaScript and Go it is essentially [a-zA-Z0-9_]; Python string patterns and several other engines include Unicode characters by default. See the engine table below. Add a quantifier to match a run of them, so \w+ matches one or more word characters in a row (\w+ on "snake_case 42" matches snake_case and then 42), and \w* matches zero or more. Its negation, \W, matches anything that is not a word character.
For the ASCII definition, the word characters are:
| Character class | Members |
|---|---|
| Letters | a-z, A-Z |
| Digits | 0-9 |
| Underscore | _ |
The underscore is a word character: \bsnake\b does not match inside snake_case, but it does match inside snake-case. The longer pattern \bsnake-case\b also matches the complete snake-case string; its outer boundary assertions do not forbid punctuation inside the match.
Anything not in \w is in \W: spaces, tabs, punctuation, hyphens, and every non-ASCII letter or symbol depending on the engine and its Unicode mode.
Whole-word matching: spaces, hyphens, and underscores
For JavaScript /\bcat\b/ and Python re.search(r"\bcat\b", text):
| Text | Match? | Why |
|---|---|---|
cat | Yes | Both outer edges are boundaries |
a cat! | Yes | Space and punctuation are non-word characters |
cat-food | Yes | Hyphen is not a word character |
cat_food | No | Underscore is a word character |
cat2 | No | A digit is a word character |
scatter | No | The substring is inside a larger word |
Do not add the JavaScript g flag to a regex you repeatedly call with .test() unless you deliberately manage its state.
Where \b matches: the four positions
A word boundary exists at any position where one side is a word character and the other side is not (including string start/end). The four cases:
| Position | When it matches | Example |
|---|---|---|
| Start of string before a word char | \bcat against "cat sat" | matches at index 0 |
| End of string after a word char | cat\b against "the cat" | cat starts at index 4; the boundary is at index 7 |
| After non-word, before word | \bcat\b against "the cat sat" | matches the standalone cat |
| After word, before non-word | same as above, the trailing edge of cat | matches |
What \b does NOT match: positions where both sides are word characters (\bcat\b against "scatter" finds no match) or both sides are non-word characters ("!@#" has no word boundaries).
| Pattern | Input | Matches | Doesn't match |
|---|---|---|---|
\bbook\b | the book! | book | |
\bbook\b | notebook | the substring is inside a word | |
\bbook\b | bookstore | trailing edge is word-to-word | |
\bdog\b | bulldog ran | leading edge is word-to-word | |
\b\d+\b | room 42 floor 3 | 42, 3 | |
\b[A-Z]+\b | using SQL today | SQL |
Negated word boundary: \B
\B matches every position that \b does NOT, namely positions where both sides are word characters, or both sides are non-word characters. It's the assertion for "match this substring only when it is inside a word":
| Pattern | Input | Matches | Why |
|---|---|---|---|
\Bis\B | this island | no match | each is touches a word edge |
\Boo\B | book | oo inside book | both sides are word chars |
\Bing\B | singing | ing (middle) | not standalone |
ing\B | singing | ing not at end | end position is word→string-end |
\Bed | bedding | matches inside bedding | left side is word char |
The classic use: highlight every occurrence of a sequence as a substring but skip the standalone form. \Bing\b matches ing at the end of a word but not the standalone word "ing".
Engine compatibility
Word boundary support varies by engine, especially around Unicode. The differences matter when you're writing patterns that need to work in more than one runtime.
| Engine | \b and \B | Unicode-aware by default | Notes |
|---|---|---|---|
| JavaScript | yes | no | u or v alone does not make \w or \b Unicode-wide. Case folding with i adds a few characters; use property escapes for an explicit Unicode token rule. |
Python (re) | yes | depends on flag | In Python 3, re.UNICODE is the default for str patterns; explicit re.A (re.ASCII) reverts to ASCII-only. For bytes patterns the default is ASCII. |
Python (regex package) | yes | yes by default | The third-party regex package is Unicode-aware by default and exposes finer control with the (?V1) version flag. |
Java (java.util.regex) | yes | no by default | \w and \b are ASCII unless you set Pattern.UNICODE_CHARACTER_CLASS (or use (?U) inline). The UNICODE_CASE flag is separate and only affects case-insensitive matching. |
| PCRE / PCRE2 / PHP | yes | optional | (*UCP) changes word-character properties; UTF mode handles encoding. In PHP, /u enables UTF mode but does not by itself enable UCP. Use /(*UCP)pattern/u when both are required. |
.NET (System.Text.RegularExpressions) | yes | yes by default | Word characters and boundaries are Unicode-aware out of the box. RegexOptions.ECMAScript restricts both to ASCII. |
| Ruby (Onigmo) | yes | engine-specific | Do not assume \w and word-boundary Unicode semantics are identical; use explicit classes and test your Ruby version. |
Go (regexp, RE2) | yes | no | Go's regexp is ASCII for \w and \b and has no Unicode-word flag. For Unicode word matching, match candidate tokens with [\p{L}\p{N}_]+ and check surrounding characters in code. Go regexp has no lookarounds. |
Rust (regex crate) | yes | yes when Unicode is enabled (default) | The default crate supports Unicode boundaries. (?-u:\b) requests an ASCII boundary; available syntax also depends on compiled features. |
| POSIX BRE / ERE | no | n/a | Word-boundary syntax is an implementation extension. GNU grep supports \b, \<, and \>; grep -w is available in GNU and BSD grep. |
For the broader cross-engine reference, see the Regex Cheat Sheet.
Unicode word boundaries
In JavaScript, adding u does not turn \b into a Unicode word segmenter. These results follow from the mostly ASCII definition of \w:
/\bna\b/.test("naïve"); // true: ï is not a JS word character
/\bna\b/u.test("naïve"); // true: u does not change that
/\bcafé\b/u.test("café break"); // false: é and the space are both non-word
/\bnaïve\b/u.test("naïve"); // true: the outer n/e edges are word edgesTo treat letters, combining marks, numbers, and underscore as a token, use an explicit rule in modern JavaScript:
const cafe = /(?<![\p{L}\p{M}\p{N}_])café(?![\p{L}\p{M}\p{N}_])/u;
cafe.test("café break"); // true
cafe.test("caféteria"); // falseThis defines one token policy; it is not language-aware segmentation. For text without space-delimited words, consider Intl.Segmenter. MDN documents JavaScript's boundary definition.
Python 3 string patterns use Unicode word characters by default:
import re
bool(re.search(r"\bcafé\b", "café break")) # True
bool(re.search(r"\bcafé\b", "café break", re.A)) # Falsere.A switches to ASCII rules; byte patterns have different defaults. See the Python re reference. In PCRE2/PHP, UTF encoding and Unicode character properties are separate options; PCRE2 documents (*UCP). Perl's \b{wb} is not portable PCRE2 syntax.
Lookaround alternative for finer control
\b is a yes/no assertion. When you need to assert which kind of character comes before or after, for example "preceded by whitespace specifically, not punctuation", use lookarounds instead:
| Goal | \b pattern | Lookaround alternative |
|---|---|---|
| Standalone whole word | \bcat\b | (?<!\w)cat(?!\w) |
| Preceded only by space (not punctuation) | not possible | (?<=\s)cat\b |
| Followed only by space or end-of-string | cat\b (too broad) | `cat(?=\s |
| Treat underscore as a separator | \bid\b does not match _id | (?<![A-Za-z0-9])id(?![A-Za-z0-9]) |
The last case is particularly useful when working with identifiers: \b treats _ as a word character (so \bid\b won't match the id inside user_id). If you specifically want to find id as a standalone token even when adjacent to underscore, use the explicit lookaround.
Python's built-in re requires fixed-width lookbehind. JavaScript supports lookbehind in modern runtimes; Go's regexp and Rust's regex crate do not support it. Check your engine before copying a lookaround alternative.
Word boundaries in Python and JavaScript
These two dominate, so here is the canonical whole-word match in each. The pattern is the same; what differs is how you express it and how Unicode behaves.
In Python, use a raw string (r"...") so the backslash reaches the regex engine instead of being eaten as a string escape. r"\bword\b" is the idiomatic form:
import re
re.findall(r"\bword\b", "word wordsmith password word.") # ['word', 'word']
re.sub(r"\bcat\b", "dog", "cat scatter cat") # 'dog scatter dog'
bool(re.search(r"\bcat\b", "the cat sat")) # TruePython 3 is Unicode-aware by default for str patterns, so r"\bnaïve\b" matches naïve with no extra flag. Pass re.A (re.ASCII) if you specifically want ASCII-only boundaries.
In JavaScript, write the literal with a single backslash (/\bword\b/), or double it when building from a string with new RegExp("\\bword\\b"):
"word wordsmith password word.".match(/\bword\b/g); // ['word', 'word']
"cat scatter cat".replace(/\bcat\b/g, "dog"); // 'dog scatter dog'
/\bcat\b/.test("the cat sat"); // trueJavaScript keeps mostly ASCII word-character semantics even with u or v. For non-ASCII token edges, use an explicit Unicode property class or a segmenter. More on that in Unicode word boundaries above.
Common use cases with examples
1. Whole-word find and replace
The most common use of \b. Rename a variable in code without mangling longer identifiers:
# GNU sed (not portable to every sed): rename 'count' to 'total' but skip 'counter', 'counterpart'
sed -E 's/\bcount\b/total/g' file.txt# Python: same
import re
new = re.sub(r"\bcount\b", "total", source)2. Highlight search terms
const term = "react";
const re = new RegExp(`\\b${term}\\b`, "giu");
return text.replace(re, m => `<mark>${m}</mark>`);The \b anchors prevent highlighting "react" inside "reaction" or "reactor".
3. Extract whole numbers from text
re.findall(r"\b\d+\b", "room 42 on floor 3 has 1024 widgets")
# ['42', '3', '1024']4. Match log tokens precisely
# Match LEVEL tokens in a log file: INFO, WARN, ERROR
re.findall(r"\b(?:INFO|WARN|ERROR)\b", log_line)Without \b, the pattern would also match ERROR inside ERROR_COUNT.
5. Validate identifier-like strings
// Match identifiers that are at least 3 chars, alphanumeric + underscore
const isIdentifier = (s) => /^\w{3,}$/.test(s);For input-validation patterns specifically, the Regex Anchors article covers ^ and $ which often pair with \b for full-string assertions.
Common mistakes
Mistake 1: assuming \b separates hyphens. \b treats - as a non-word character, so \bword\b matches word in word-art. If you don't want that, use the explicit lookaround (?<![A-Za-z0-9_-])word(?![A-Za-z0-9_-]).
Mistake 2: assuming u fixes JavaScript word boundaries. It enables Unicode syntax and code-point handling, but does not make every Unicode letter a \w character. Test the edges of the particular token, not just its interior.
Mistake 3: assuming GNU extensions are POSIX. Standard BRE/ERE does not define \b. On GNU or BSD grep, grep -w 'word' file.txt is convenient. For a portable explicit rule, use grep -E '(^|[^[:alnum:]_])word([^[:alnum:]_]|$)' file.txt; this selects lines and consumes the separators as part of the match.
Mistake 4: thinking \B is "the opposite end" of \b. \B is "no boundary HERE", not "boundary on the other side". \Bbook\B matches book only when both edges are inside a word, which is rare for the whole word book (it would need to be inside something like bookbookkeeper).
Mistake 5: confusing \b with ^ and $. ^ and $ anchor to the start and end of the line (or string with the appropriate flag); \b anchors to the start or end of a word. Both are zero-width but operate at different scales. See the Regex Anchors guide for the line/string anchors.
Mistake 6: copying a Python Unicode pattern to Go. Go accepts \b but defines it in ASCII terms. Match Unicode token candidates and inspect their neighbours in code; a lookaround does not compile in Go's built-in regexp package.
What to do next
For more advanced word-matching patterns:
- Regex Lookaheads and Lookbehinds: an alternative to
\bwhen you need finer control over what comes before or after. - Regex Anchors:
^and$for line and string boundaries, the natural complement to\b. - Regex Capturing Groups and Backreferences: when you need to reuse a matched word elsewhere in the pattern.
For specific real-world patterns that build on word boundaries:
- Match Email Address:
\bis essential for picking emails out of prose. - Match URLs: same idea, anchored to whole-token extraction.
- Match Domain Name: domain extraction from logs and mixed text.
- Match Numbers:
\b\d+\bis the canonical whole-number pattern. - Match HTML Tags: token-level matching against markup.
For the one-page reference with every regex shortcut on one page, see the Regex Cheat Sheet.
FAQ
It matches a position between a word character and a non-word character, including a string edge next to a word character. It consumes no text. Wrap a word with two boundaries to avoid matching it inside a longer word.
Yes in the usual word-character definitions. A whole-word pattern for id does not match id in user_id. To treat underscore as a separator, use an explicit boundary class that leaves underscore out.
The first asserts a word boundary; the second asserts that the current position is not a word boundary. Both are zero-width. Python before 3.14 has an additional empty-string exception for the non-boundary assertion.
No. Use Unicode property escapes to define the token characters you need, or Intl.Segmenter for language-aware word segmentation. The Unicode flag alone does not change the usual ASCII-oriented word-character definition.
Yes, when the other side is a word character. A whole-word pattern for cat matches cat in cat-food, but not in cat_food. Include hyphen in a custom token class if you want to treat cat-food as one token.
See also
- Regex Anchors:
^and$are the full-string equivalents; word boundaries are the per-token version - Regex Lookaheads and Lookbehinds: a replacement for
\bwhen you need custom boundary characters - Validate Password Strength with Regex: a counterexample, anchored validation that uses
^/$rather than\b - Regex Capturing Groups and Backreferences:
\b(\w+)\bis the standard whole-word capture pattern - Regex Cheat Sheet: the wider syntax and engine compatibility reference
Recommended books
Word boundaries are one of the most misunderstood zero-width assertions. If you want the concepts properly grounded:
- Learning Regular Expressions (Ben Forta). The gentlest on-ramp: short, current, and example-driven. A good first book if you are still finding your feet.
- Regular Expressions Cookbook (Jan Goyvaerts and Steven Levithan, 2nd edition). Problem-then-solution recipes across eight languages (JavaScript, Python, PHP, Java, .NET, Ruby, Perl, VB). The one to keep next to the keyboard.
- Mastering Regular Expressions (Jeffrey Friedl, 3rd edition). The definitive deep-dive on how regex engines actually work: backtracking, NFA versus DFA, and the optimisation that makes a pattern fast or catastrophic. Dense, and unmatched once you are past the basics.





