pageClass | sidebarDepth | title | description | since |
---|---|---|---|---|
rule-details |
0 |
regexp/prefer-character-class |
enforce using character class |
v0.4.0 |
💼 This rule is enabled in the ✅ plugin:regexp/recommended
config.
🔧 This rule is automatically fixable by the --fix
CLI option.
enforce using character class
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 a
s, the regex ^[\wa]+b$
will reject a string of n many a
s in O(n).
This rule might not be able to merge all single-character alternatives.
/* eslint regexp/prefer-character-class: "error" */
/* ✓ GOOD */
var foo = /[abc]/
var foo = /(?:a|b)/
/* ✗ BAD */
var foo = /a|b|c/
var foo = /(a|b|c)c/
var foo = /.|\s/
var foo = /(\w|\d)+:/
{
"regexp/prefer-character-class": [
"error",
{
"minAlternatives": 3
}
]
}
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.
This rule was introduced in eslint-plugin-regexp v0.4.0