Skip to content

regexp/prefer-character-class

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

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

enforce using character class

📖 Rule Details

Instead of single-character alternatives (e.g. (?:a|b|c)), character classes (e.g. [abc]) should be preferred.

The main reason for doing this is performance. Character classes don't require backtracking and are heavily optimized by the regex engine. On the other hand, alternatives are usually quite tricky to optimize.

Character classes are also safer than alternatives because they don't require backtracking. While ^(?:\w|a)+b$ will take O(2^n) time to reject a string of n many as, the regex ^[\wa]+b$ will reject a string of n many as in O(n).

Limitations

This rule might not be able to merge all single-character alternatives.

Now loading...

🔧 Options

json5
{
  "regexp/prefer-character-class": [
    "error",
    {
        "minAlternatives": 3
    }
  ]
}

minAlternatives: integer

This number controls how many character alternatives have to be present for them to be merged. By default, there need to be at least 3 alternatives.

Note that this option does not affect character alternatives where the characters overlap. These alternatives will always be merged to prevent excessive backtracking.

🚀 Version

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

🔍 Implementation