regexUnnecessaryCharacterClasses
Reports character classes that wrap a single element that does not require brackets.
✅ This rule is included in the tslogicalandlogicalStrictpresets.
Reports character classes that wrap a single element that does not require brackets.
A character class like [a] or [\d] can be simplified to just a or \d.
Examples
Section titled “Examples”Single Character Class
Section titled “Single Character Class”A character class with a single character can be unwrapped.
const const pattern: RegExp
pattern = /[a]/;const const pattern: RegExp
pattern = /a/;Escape Sequence Class
Section titled “Escape Sequence Class”A character class with a single escape sequence can be unwrapped.
const const pattern: RegExp
pattern = /[\d]/;const const pattern: RegExp
pattern = /\d/;RegExp Constructor
Section titled “RegExp Constructor”The rule also checks regex patterns in RegExp constructor calls.
const const pattern: RegExp
pattern = new var RegExp: RegExpConstructornew (pattern: RegExp | string, flags?: string) => RegExp (+2 overloads)
RegExp("[a]");const const pattern: RegExp
pattern = new var RegExp: RegExpConstructornew (pattern: RegExp | string, flags?: string) => RegExp (+2 overloads)
RegExp("a");Valid Cases
Section titled “Valid Cases”These cases are valid and will not be reported:
// Negated classesconst const negated: RegExp
negated = /[^a]/;
// Backspace escape (has special meaning in character class)const const backspace: RegExp
backspace = /[\b]/;
// Multiple elementsconst const multiple: RegExp
multiple = /[ab]/;
// Character rangesconst const range: RegExp
range = /[a-z]/;
// Equals sign (commonly used in regex for readability)const const equals: RegExp
equals = /[=]/;Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If you prefer to use character classes for consistency or readability, even when they contain only a single element, you might prefer to disable this rule.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”
Made with ❤️🔥 around the world by
the Flint team and contributors.