]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/rules/prefer-named-capture-group.md
ff8790c836d62ed103fa1267c6e0bf4c0afc7b96
[pve-eslint.git] / eslint / docs / rules / prefer-named-capture-group.md
1 # Suggest using named capture group in regular expression (prefer-named-capture-group)
2
3 With the landing of ECMAScript 2018, named capture groups can be used in regular expressions, which can improve their readability.
4
5 ```js
6 const regex = /(?<year>[0-9]{4})/;
7 ```
8
9 ## Rule Details
10
11 This rule is aimed at using named capture groups instead of numbered capture groups in regular expressions.
12
13 Examples of **incorrect** code for this rule:
14
15 ```js
16 /*eslint prefer-named-capture-group: "error"*/
17
18 const foo = /(ba[rz])/;
19 const bar = new RegExp('(ba[rz])');
20 const baz = RegExp('(ba[rz])');
21
22 foo.exec('bar')[1]; // Retrieve the group result.
23 ```
24
25 Examples of **correct** code for this rule:
26
27 ```js
28 /*eslint prefer-named-capture-group: "error"*/
29
30 const foo = /(?<id>ba[rz])/;
31 const bar = new RegExp('(?<id>ba[rz])');
32 const baz = RegExp('(?<id>ba[rz])');
33
34 foo.exec('bar').groups.id; // Retrieve the group result.
35 ```
36
37 ## When Not To Use It
38
39 If you are targeting ECMAScript 2017 and/or older environments, you can disable this rule, because this ECMAScript feature is only supported in ECMAScript 2018 and/or newer environments.
40
41 ## Related Rules
42
43 * [no-invalid-regexp](./no-invalid-regexp.md)