版本

no-empty-character-class

禁止在正規表示式中使用空的字元類別

推薦

設定檔中使用來自 @eslint/jsrecommended 設定會啟用此規則

由於正規表示式中空的字元類別不匹配任何內容,它們可能是輸入錯誤。

const foo = /^abc[]/;

規則詳情

此規則禁止在正規表示式中使用空的字元類別。

此規則的 錯誤 程式碼範例

在遊樂場開啟
/*eslint no-empty-character-class: "error"*/

/^abc[]/.test("abcdefg"); // false
"abcdefg".match(/^abc[]/); // null

/^abc[[]]/v.test("abcdefg"); // false
"abcdefg".match(/^abc[[]]/v); // null

/^abc[[]--[x]]/v.test("abcdefg"); // false
"abcdefg".match(/^abc[[]--[x]]/v); // null

/^abc[[d]&&[]]/v.test("abcdefg"); // false
"abcdefg".match(/^abc[[d]&&[]]/v); // null

const regex = /^abc[d[]]/v;
regex.test("abcdefg"); // true, the nested `[]` has no effect
"abcdefg".match(regex); // ["abcd"]
regex.test("abcefg"); // false, the nested `[]` has no effect
"abcefg".match(regex); // null
regex.test("abc"); // false, the nested `[]` has no effect
"abc".match(regex); // null

此規則的 正確 程式碼範例

在遊樂場開啟
/*eslint no-empty-character-class: "error"*/

/^abc/.test("abcdefg"); // true
"abcdefg".match(/^abc/); // ["abc"]

/^abc[a-z]/.test("abcdefg"); // true
"abcdefg".match(/^abc[a-z]/); // ["abcd"]

/^abc[^]/.test("abcdefg"); // true
"abcdefg".match(/^abc[^]/); // ["abcd"]

已知限制

此規則不會回報呼叫 RegExp 建構函式的字串參數中空的字元類別。

當此規則回報正確程式碼時的假陰性範例

/*eslint no-empty-character-class: "error"*/

const abcNeverMatches = new RegExp("^abc[]");

版本

此規則在 ESLint v0.22.0 中引入。

資源

變更語言