# regexp/no-unused-capturing-group

disallow unused capturing group

  • ⚙️ This rule is included in "plugin:regexp/recommended".
  • 🔧 The --fix option on the command line (opens new window) can automatically fix some of the problems reported by this rule.

# 📖 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

{
  "regexp/no-unused-capturing-group": ["error", {
    "fixable": 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.

# 🚀 Version

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

# 🔍 Implementation