版本

prefer-named-capture-group

強制在正規表示式中使用具名捕獲群組

💡 hasSuggestions

此規則報告的一些問題可以透過編輯器的建議手動修正

規則詳細資訊

隨著 ECMAScript 2018 的推出,具名捕獲群組可以用在正規表示式中,這可以提高它們的可讀性。此規則旨在在正規表示式中使用具名捕獲群組,而不是編號捕獲群組。

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

或者,如果您的目的不是捕獲結果,而只是表達替代方案,請使用非捕獲群組

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

此規則的不正確程式碼範例

在遊樂場中開啟
/*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.

此規則的正確程式碼範例

在遊樂場中開啟
/*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.

何時不使用它

如果您以 ECMAScript 2017 和/或更舊的環境為目標,您不應該使用此規則,因為此 ECMAScript 功能僅在 ECMAScript 2018 和/或更新的環境中支援。

版本

此規則是在 ESLint v5.15.0 中引入的。

資源

變更語言