Skip to content

regexp/optimal-quantifier-concatenation

💼 This rule is enabled in the ✅ plugin:regexp/recommended config.

🔧 This rule is automatically fixable by the --fix CLI option.

require optimal quantifiers for concatenated quantifiers

📖 Rule Details

If two quantified characters, character classes, or characters are concatenated, the quantifiers can be optimized if either of the characters elements is a subset of the other.

Let's take \d+\w+ as an example.
This can be optimized to the equivalent pattern \d\w+. Not only is the optimized pattern simpler, it is also faster because the first pattern might take up to O(n^2) steps to fail while the optimized pattern will fail after at most O(n) steps. Generally, the optimized pattern will take less backtracking steps to fail.

Choosing optimal quantifiers does not only make your patterns simpler but also faster and most robust against ReDoS attacks.

Now loading...

🔧 Options

json5
{
  "regexp/optimal-quantifier-concatenation": [
    "error",
    {
        "capturingGroups": "report"
    }
  ]
}
{
  "regexp/optimal-quantifier-concatenation": [
    "error",
    {
        "capturingGroups": "report"
    }
  ]
}

capturingGroups

The type of concatenation this rule reports might be intentional around capturing groups. This option allows you to turn off false unfixable reports around capturing groups.

  • capturingGroups: "report" (default)

    Concatenations around quantifiers will be reported.

  • capturingGroups: "ignore"

    Concatenations around quantifiers will not be reported.

    If this option is used, it is recommended to have the regexp/no-super-linear-backtracking rule enabled to protect against ReDoS.

📚 Further reading

🚀 Version

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

🔍 Implementation