字边界断言:\\b,\\B

字边界断言检查字符串中的当前位置是否是字边界。单词边界是指下一个字符是单词字符而前一个字符不是单词字符,反之亦然。

¥A word boundary assertion checks if the current position in the string is a word boundary. A word boundary is where the next character is a word character and the previous character is not a word character, or vice versa.

语法

¥Syntax

regex
\b
\B

描述

¥Description

\b 断言字符串中的当前位置是字边界。\B 否定该断言:它断言当前位置不是字边界。两者都是断言,因此与其他 字符转义字符类转义 不同,\b\B 不消耗任何字符。

¥\b asserts that the current position in the string is a word boundary. \B negates the assertion: it asserts that the current position is not a word boundary. Both are assertions, so unlike other character escapes or character class escapes, \b and \B don't consume any characters.

一个单词字符包括以下内容:

¥A word character includes the following:

  • 字母(A–Z、a–z)、数字(0–9)和下划线(_)。
  • 如果正则表达式为 Unicode 感知 并且设置了 i 标志,则其他 Unicode 字符将通过 表壳折叠 规范化为上述字符之一。

单词字符也由 \w 字符类转义 匹配。

¥Word characters are also matched by the \w character class escape.

越界输入位置被视为非单词字符。例如,以下是成功匹配:

¥Out-of-bounds input positions are considered non-word characters. For example, the following are successful matches:

js
/\ba/.exec("abc");
/c\b/.exec("abc");

/\B /.exec(" abc");
/ \B/.exec("abc ");

示例

¥Examples

检测单词

¥Detecting words

以下示例检测字符串是否包含单词 "thanks" 或 "谢谢":

¥The following example detects if a string contains the word "thanks" or "thank you":

js
function hasThanks(str) {
  return /\b(thanks|thank you)\b/i.test(str);
}

hasThanks("Thanks! You helped me a lot."); // true
hasThanks("Just want to say thank you for all your work."); // true
hasThanks("Thanksgiving is around the corner."); // false

警告:并非所有语言都有明确定义的单词边界。如果你使用的是中文或泰语等没有空格分隔符的语言,请使用更高级的库(如 Intl.Segmenter)来搜索单词。

¥Warning: Not all languages have clearly defined word boundaries. If you are working with languages like Chinese or Thai, where there are no whitespace separators, use a more advanced library like Intl.Segmenter to search for words instead.

规范

Specification
ECMAScript Language Specification
# prod-Assertion

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看