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;

另見