Index

no-control-regex

禁止在正则表达式中使用控制字符

Recommended

配置文件 中使用来自 @eslint/jsrecommended 配置可以启用此规则

控制字符是 ASCII 范围 0-31 中的特殊、不可见字符。这些字符在 JavaScript 字符串中很少使用,因此包含明确匹配这些字符元素的正则表达式很可能是错误的。

🌐 Control characters are special, invisible characters in the ASCII range 0-31. These characters are rarely used in JavaScript strings so a regular expression containing elements that explicitly match these characters is most likely a mistake.

规则详情

🌐 Rule Details

此规则不允许控制字符和某些与正则表达式中的控制字符匹配的转义序列。

🌐 This rule disallows control characters and some escape sequences that match control characters in regular expressions.

正则表达式模式的以下元素被认为是可能的键入错误,因此被此规则禁止:

🌐 The following elements of regular expression patterns are considered possible errors in typing and are therefore disallowed by this rule:

  • \x00\x1F 的十六进制字符转义。
  • Unicode 字符转义从 \u0000\u001F
  • Unicode 代码点转义从 \u{0}\u{1F}
  • 从 U+0000 到 U+001F 的未转义原始字符。

此规则允许使用诸如 \t\n 的控制转义。

🌐 Control escapes such as \t and \n are allowed by this rule.

此规则的错误代码示例:

🌐 Examples of incorrect code for this rule:

在线运行
/*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

符合此规则的正确代码示例:

🌐 Examples of correct code for this rule:

在线运行
/*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");

选项

🌐 Options

此规则没有选项。

🌐 This rule has no options.

已知限制

🌐 Known Limitations

在检查 RegExp 构造函数调用时,此规则会检查已求值的正则表达式模式。因此,尽管此规则旨在允许诸如 \t 的语法,但它不允许 new RegExp("\t"),因为已求值的模式("\t" 的字符串值)包含原始控制字符(TAB 字符)。

🌐 When checking RegExp constructor calls, this rule examines evaluated regular expression patterns. Therefore, although this rule intends to allow syntax such as \t, it doesn’t allow new RegExp("\t") since the evaluated pattern (string value of "\t") contains a raw control character (the TAB character).

/*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")

🌐 There is no difference in behavior between new RegExp("\t") and new RegExp("\\t"), and the intention to match the TAB character is clear in both cases. They are equally valid for the purpose of this rule, but it only allows new RegExp("\\t").

何时不使用

🌐 When Not To Use It

如果你需要使用控制字符模式匹配,那么你应该关闭此规则。

🌐 If you need to use control character pattern matching, then you should turn this rule off.

版本

此规则是在 ESLint v0.1.0 中引入。

资源