prefer-named-capture-group

在正则表达式中强制使用命名捕获组

💡 hasSuggestions

此规则报告的一些问题可通过编辑器建议手动修复

规则详情

¥Rule Details

随着 ECMAScript 2018 的落地,命名捕获组可以用在正则表达式中,可以提高其可读性。此规则旨在在正则表达式中使用命名捕获组而不是编号捕获组:

¥With the landing of ECMAScript 2018, named capture groups can be used in regular expressions, which can improve their readability. This rule is aimed at using named capture groups instead of numbered capture groups in regular expressions:

const regex = /(?<year>[0-9]{4})/;

或者,如果你的意图不是捕获结果,而只是表达替代方案,请使用非捕获组:

¥Alternatively, if your intention is not to capture the results, but only express the alternative, use a non-capturing group:

const regex = /(?:cauli|sun)flower/;

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

在线运行
/*eslint prefer-named-capture-group: "error"*/

const foo = /(ba[rz])/;
const bar = new RegExp('(ba[rz])');
const baz = RegExp('(ba[rz])');

foo.exec('bar')[1]; // Retrieve the group result.

此规则的正确代码示例:

¥Examples of correct code for this rule:

在线运行
/*eslint prefer-named-capture-group: "error"*/

const foo = /(?<id>ba[rz])/;
const bar = new RegExp('(?<id>ba[rz])');
const baz = RegExp('(?<id>ba[rz])');
const xyz = /xyz(?:zy|abc)/;

foo.exec('bar').groups.id; // Retrieve the group result.

何时不使用

¥When Not To Use It

如果你的目标是 ECMAScript 2017 和/或更早的环境,则不应使用此规则,因为此 ECMAScript 功能仅在 ECMAScript 2018 和/或更新的环境中受支持。

¥If you are targeting ECMAScript 2017 and/or older environments, you should not use this rule, because this ECMAScript feature is only supported in ECMAScript 2018 and/or newer environments.

版本

此规则是在 ESLint v5.15.0 中引入。

资源

ESLint 中文网
粤ICP备13048890号