Skip to content

regexp/no-unused-capturing-group

💼 This rule is enabled in the following configs: 🟢 flat/recommended, 🔵 recommended.

🔧💡 This rule is automatically fixable by the --fix CLI option and manually fixable by editor suggestions.

disallow unused capturing group

📖 Rule Details

This rule reports unused capturing groups.

Now loading...

Why no unused capturing groups?

Many people use capturing groups instead of non-capturing groups for convenience. () is simpler and feels more natural than the cryptic-looking (?:).

However, using capturing groups in place of non-capturing groups also has negative consequences.

Performance

Capturing groups are slower than non-capturing groups.

This is by design. Capturing groups (as the name suggests) captured their matched text. The regex engine has to do extra work every time a capturing group is matched compared to a non-capturing group.

Code smell

A capturing group is intended to store its matched text so it can later be used, e.g. in text replacements.

That makes a capturing group quite similar to a variable, in that its value (the captured text) is stored (by the regex engine) and can be accessed afterward (by the developer). However, if the captured text is not used, then the capturing group will essentially be an unused variable. This makes the regex harder to understand because other developers will have to constantly ask themselves: "Is this a capturing group because the captured text will be used later on in the code, or because () is faster to type?"

Using capturing groups only if the captured text is used makes their usage unambiguous and easier for others to understand.

🔧 Options

json
{
  "regexp/no-unused-capturing-group": ["error", {
    "fixable": false,
    "allowNamed": false
  }]
}
  • fixable: true | false

    This option controls whether the rule is fixable. Defaults to false.

    This rule is not fixable by default. Unused capturing groups can indicate a mistake in the code that uses the regex, so changing the regex might not be the right fix. When enabling this option, be sure to carefully check its changes.

  • allowNamed: true | false

    Whether unused named capturing groups are allowed. Defaults to false.

    Sometimes named capturing groups can be used to document a regex. In such cases, it can be acceptable to have unused named capturing groups. This option is disabled by default to prevent mistakes.

🚀 Version

This rule was introduced in eslint-plugin-regexp v0.6.0

🔍 Implementation