SyntaxError: 字符类转义在正则表达式中的类范围内不可用
当 Unicode 感知 正则表达式模式包含 字符类,其中字符范围的边界是另一个字符类,例如 字符类转义 时,将发生 JavaScript 异常 "字符类转义不能在正则表达式中的类范围内使用"。
消息
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)
错误类型
哪里出错了?
示例
无效情况
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;