字符类转义:\\d、\\D、\\w、\\W、\\s、\\S

字符类转义是表示一组字符的转义序列。

¥A character class escape is an escape sequence that represents a set of characters.

语法

¥Syntax

regex
\d, \D
\s, \S
\w, \W

注意:, 不是语法的一部分。

¥Note: , is not part of the syntax.

描述

¥Description

字符转义 不同,字符类转义代表一组预定义的字符,很像 字符类。支持以下字符类:

¥Unlike character escapes, character class escapes represent a predefined set of characters, much like a character class. The following character classes are supported:

\d

: 匹配任意数字字符。相当于 [0-9]

\w

匹配任何单词字符,其中单词字符包括字母(A–Z、a–z)、数字(0–9)和下划线(_)。如果正则表达式为 Unicode 感知 并且设置了 i 标志,它还会匹配通过 表壳折叠 规范化为上述字符之一的其他 Unicode 字符。

\s

匹配任意 whitespace行终止符 字符。

大写形式 \D\W\S 分别为 \d\w\s 创建补码字符类。它们匹配不属于小写形式匹配的字符集中的任何字符。

¥The uppercase forms \D, \W, and \S create complement character classes for \d, \w, and \s, respectively. They match any character that is not in the set of characters matched by the lowercase form.

Unicode 字符类转义\p\P 开头,但仅在 Unicode 识别模式 中受支持。在 Unicode 不识别模式下,它们是 身份逃避 代表 pP 字符。

¥Unicode character class escapes start with \p and \P, but they are only supported in Unicode-aware mode. In Unicode-unaware mode, they are identity escapes for the p or P character.

字符类转义可以在 字符类 中使用。但是,它们不能用作字符范围的边界,仅允许作为 已弃用的 Web 兼容性语法,并且你不应依赖它。

¥Character class escapes can be used in character classes. However, they cannot be used as boundaries of character ranges, which is only allowed as a deprecated syntax for web compatibility, and you should not rely on it.

示例

¥Examples

按空格分割

¥Splitting by whitespace

以下示例将字符串拆分为单词数组,支持各种空白分隔符:

¥The following example splits a string into an array of words, supporting all kinds of whitespace separators:

js
function splitWords(str) {
  return str.split(/\s+/);
}

splitWords(`Look at the stars
Look  how they\tshine for you`);
// ['Look', 'at', 'the', 'stars', 'Look', 'how', 'they', 'shine', 'for', 'you']

规范

Specification
ECMAScript Language Specification
# prod-CharacterClassEscape

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看