# prefer-named-capture-group

> Require capture groups in regular expressions to have a name

You read a numbered group as `match[1]`, which says nothing about what it holds, and the number shifts when you add a group in front of it. You read a named group as `match.groups.year`, and that stays correct when the pattern changes.

A group that's only there for grouping can be non-capturing: `(?:...)`.

A constant string passed to `RegExp()` or `new RegExp()` is checked too. The report comes with two suggestions: name the group, or make it non-capturing.

{/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */}

## Configure

Off by default. To turn it on:

```toml bunfig.toml
[lint.rules]
"prefer-named-capture-group" = "error" # or "warn"
```

{/* End of the generated section. */}

## Examples

Reported:

{/* bad {"count": 3} */}
```js
const date = /(\d{4})-(\d{2})/.exec(input);
const year = date[1];

const version = new RegExp("v([0-9]+)");
```

Not reported:

{/* good */}
```js
const date = /(?<year>\d{4})-(?<month>\d{2})/.exec(input);
const year = date.groups.year;

const isImage = /\.(?:png|jpe?g)$/.test(file);
```
