regexNamedCaptureGroups
Reports capturing groups in regular expressions that do not have a name.
✅ This rule is included in the ts preset.
Named capture groups ((?<name>...)) provide several advantages over numbered capture groups:
- They make regex patterns more self-documenting
- They are easier to reference in replacement strings
- They don’t break when the order of groups changes
- They work better with destructuring in match results
If a capture is not actually needed, consider using a non-capturing group (?:...) instead.
This rule reports capturing groups in regular expressions that do not have a name.
Examples
Section titled “Examples”const pattern = /([0-9]{4})-([0-9]{2})-([0-9]{2})/;const pattern = /(foo)(bar)/;const pattern = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/;// Non-capturing groups when capture is not neededconst pattern = /(?:foo)(?:bar)/;// Mix of named and non-capturing groupsconst pattern = /(?<protocol>https?):\/\/(?:www\.)?(?<domain>[^/]+)/;Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If you have a large codebase with many existing unnamed capture groups that would be difficult to refactor, you might prefer to disable this rule. Some developers also find numbered groups sufficient for simple regex patterns with few groups.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”
Made with ❤️🔥 in Boston by
Josh Goldberg and contributors.