SyntaxError: character class escape cannot be used in class range in regular expression

JavaScript 异常“字符类转义不能在正则表达式的字符类范围中使用”发生于 Unicode 感知正则表达式模式包含一个字符类,其中字符范围的边界是另一个字符类,例如字符类转义

消息

SyntaxError: Invalid regular expression: /[\s-1]/u: Invalid character class (V8-based)
SyntaxError: character class escape cannot be used in class range in regular expression (Firefox)
SyntaxError: Invalid regular expression: invalid range in character class for Unicode pattern (Safari)

错误类型

SyntaxError

哪里出错了?

字符类可以通过在两个字符之间使用连字符 (-) 来指定一个字符范围。例如,[a-z] 匹配 az 之间的任何小写字母。为了使范围有意义,范围的两个边界必须代表单个字符。如果其中一个边界实际上代表多个字符,则会生成错误。在v 模式字符类中,只有字符类转义符允许在字符类内部使用;在v 模式字符类中,如果其中一个边界是另一个 [...] 字符类,也会发生这种情况。

在 Unicode 非感知模式下,此语法会导致 - 成为字面量字符而不是生成错误,但这是一种已弃用的语法,不应依赖它。

示例

无效案例

js
/[\s-_]/u; // \s is a character class escape for whitespace
/[A-\D]/u; // \D is a character class escape for non-digits
/[\p{L}-\p{N}]/u; // \p{L} is a character class escape for Unicode letters
/[[A-z]-_]/v; // In unicodeSets mode, character classes can be nested

有效情况

js
// Put the hyphen at the start of the character class,
// so it matches the literal character
/[-\s_]/u;
// Escape the hyphen so it also matches the literal character
/[\s\-_]/u;
// Remove the backslash so the bound is a literal character
/[A-D]/u;
// Remove the hyphen so the two bounds represent two alternatives
/[\p{L}\p{N}]/u;
// Use -- in unicodeSets mode, which represents set subtraction
/[[A-z]--_]]/v;

另见