From 8c61f5ac67682fcfec7fc6faafcf72e4b1a339ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andrzej=20W=C3=B3dkiewicz?= Date: Sat, 4 Sep 2021 02:17:21 +0200 Subject: [PATCH] Docs: add info about non-capturing groups to prefer-named-capture-group (#15009) Fixes #15007 --- docs/rules/prefer-named-capture-group.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/rules/prefer-named-capture-group.md b/docs/rules/prefer-named-capture-group.md index 197629fcd2c..2caf9518eab 100644 --- a/docs/rules/prefer-named-capture-group.md +++ b/docs/rules/prefer-named-capture-group.md @@ -1,14 +1,20 @@ # Suggest using named capture group in regular expression (prefer-named-capture-group) + +## Rule Details + 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: ```js const regex = /(?[0-9]{4})/; ``` -## Rule Details +Alternatively, if your intention is not to _capture_ the results, but only express the alternative, use a non-capturing group: -This rule is aimed at using named capture groups instead of numbered capture groups in regular expressions. +```js +const regex = /(?:cauli|sun)flower/; +``` Examples of **incorrect** code for this rule: @@ -30,6 +36,7 @@ Examples of **correct** code for this rule: const foo = /(?ba[rz])/; const bar = new RegExp('(?ba[rz])'); const baz = RegExp('(?ba[rz])'); +const xyz = /xyz(?:zy|abc)/; foo.exec('bar').groups.id; // Retrieve the group result. ```