CKTIS / JavaScript
Regular expression word boundaries and noncapturing groups
Use `\b` and `\B` to test for word boundaries, and `(?:...)` to group alternatives without adding a capture.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
\b — word-boundary assertion
\B — non-word-boundary assertion
(?:pattern) — noncapturing group
/\b(?:cat|dog)(s?)\b/ — either alternative with shared boundaries and a separate suffix captureRegular expression word boundaries and noncapturing groups solve different problems: boundaries test positions, while groups organize patterns. \b succeeds when exactly one side of the current position has a word character. \B is the opposite: both sides have a word character or neither does. Before the start and after the end of the input, a missing character counts as non-word. Neither assertion consumes characters. Inside a character class, \b has a different meaning: [\b] matches a backspace character (U+0008).
The definition of a word character is the same as for \w: A–Z, a–z, 0–9, and _, plus characters whose Unicode simple case folding yields one of those ASCII characters when i is combined with u or v. This is not language-aware word segmentation. When you need that, use Intl.Segmenter with granularity: "word" where the runtime supports it.
(?:...) groups a subpattern so you can limit the scope of | or apply a quantifier to the entire group. Text it matches is still part of the full match, but unlike (...), the group itself gets no capture number or separate slot in the exec() result. In \b(?:cat|dog)\b, both boundaries apply to both alternatives; in \bcat|dog\b, the first applies only to cat and the last only to dog.
Examples
const pattern = /\b(?:cat|dog)(s?)\b/;
const inputs = ["cats!", "dogs.", "bobcats", "cats_2", "dogmatic"];
const results = inputs.map((input) => {
const match = pattern.exec(input);
return match === null ? null : [match[0], match[1]];
});
console.log(JSON.stringify(results));
console.log(/\Bcats\b/.test("bobcats"));Result
[["cats","s"],["dogs","s"],null,null,null] true
`match[0]` is the full match, and `match[1]` comes from `(s?)`. The underscore in `cats_2` is a word character, so there is no boundary immediately after `cats`. In `bobcats`, the position before `cats` satisfies `\B`, and the position after it satisfies `\b`.
Related lessons
- JavaScript · Lesson 10 · Advanced · Version: 4