版本

no-control-regex

不允許在正規表示式中使用控制字元

建議

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

控制字元是 ASCII 範圍 0-31 中的特殊、不可見字元。這些字元很少在 JavaScript 字串中使用,因此包含明確匹配這些字元的元素的正規表示式很可能是一個錯誤。

規則詳情

此規則不允許在正規表示式中使用控制字元和一些匹配控制字元的跳脫序列。

正規表示式模式的以下元素被認為是可能的輸入錯誤,因此此規則不允許

  • \x00\x1F 的十六進位字元跳脫。
  • \u0000\u001F 的 Unicode 字元跳脫。
  • \u{0}\u{1F} 的 Unicode 碼位跳脫。
  • 從 U+0000 到 U+001F 的未跳脫原始字元。

此規則允許控制跳脫字元,例如 \t\n

此規則的錯誤程式碼範例

在 Playground 中開啟
/*eslint no-control-regex: "error"*/

const pattern1 = /\x00/;
const pattern2 = /\x0C/;
const pattern3 = /\x1F/;
const pattern4 = /\u000C/;
const pattern5 = /\u{C}/u;
const pattern6 = new RegExp("\x0C"); // raw U+000C character in the pattern
const pattern7 = new RegExp("\\x0C"); // \x0C pattern

此規則的正確程式碼範例

在 Playground 中開啟
/*eslint no-control-regex: "error"*/

const pattern1 = /\x20/;
const pattern2 = /\u0020/;
const pattern3 = /\u{20}/u;
const pattern4 = /\t/;
const pattern5 = /\n/;
const pattern6 = new RegExp("\x20");
const pattern7 = new RegExp("\\t");
const pattern8 = new RegExp("\\n");

已知限制

在檢查 RegExp 建構子呼叫時,此規則會檢查評估後的正規表示式模式。因此,雖然此規則旨在允許諸如 \t 之類的語法,但它不允許 new RegExp("\t"),因為評估後的模式("\t" 的字串值)包含原始控制字元(TAB 字元)。

/*eslint no-control-regex: "error"*/

new RegExp("\t"); // disallowed since the pattern is: <TAB>

new RegExp("\\t"); // allowed since the pattern is: \t

new RegExp("\t")new RegExp("\\t") 之間在行為上沒有差異,並且在這兩種情況下匹配 TAB 字元的意圖都很明確。它們對於此規則的目的而言同樣有效,但它僅允許 new RegExp("\\t")

何時不應使用

如果您需要使用控制字元模式匹配,則應關閉此規則。

版本

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

資源

變更語言