Skip to content

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.

const
const pattern: RegExp
pattern
= /a|b|c/;
const
const digits: RegExp
digits
= /1|2|3|4|5/;
const
const mixed: RegExp
mixed
= /a|b|[cd]/;
const
const withSets: RegExp
withSets
= /\w|\d|x/;

This rule is not configurable.

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.

Made with ❤️‍🔥 around the world by the Flint team and contributors.