版本

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 中引入。

資源

變更語言