regexCharacterClasses
Reports regex alternations that can be simplified to character classes.
✅ This rule is included in the ts stylisticStrict presets.
Character classes in regular expressions are more efficient than alternations because they don’t require backtracking. When multiple single-character alternatives are used in a regex pattern, they can be combined into a character class for better performance and readability.
Examples
Section titled “Examples”const pattern = /a|b|c/;const digits = /1|2|3|4|5/;const mixed = /a|b|[cd]/;const withSets = /\w|\d|x/;const pattern = /[abc]/;const digits = /[12345]/;const mixed = /[abcd]/;const withSets = /[\w\dx]/;// Two alternatives are allowed (below the default threshold)const twoChars = /a|b/;// Multi-character alternatives cannot be simplifiedconst multiChar = /ab|cd/;// Alternations with word boundaries or other assertionsconst withBoundary = /a|b|c\b/;Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If you prefer the readability of explicit alternations over character classes, or if your codebase has specific conventions around regex formatting, you might prefer to disable this rule. Some developers find alternations easier to read when the alternatives represent distinct concepts rather than a set of characters.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”- ESLint:
regexp/prefer-character-class
Made with ❤️🔥 in Boston by
Josh Goldberg and contributors.