# regexp/prefer-character-class
enforce using character class
- ⚙️ 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
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).
# Limitations
This rule might not be able to merge all single-character alternatives.
# 🔧 Options
Nothing.
# 🚀 Version
This rule was introduced in eslint-plugin-regexp v0.4.0