Skip to content

regexUnnecessaryCharacterClasses

Reports character classes that wrap a single element that does not require brackets.

✅ This rule is included in the ts logical and logicalStrict presets.

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.

A character class with a single character can be unwrapped.

const
const pattern: RegExp
pattern
= /[a]/;

A character class with a single escape sequence can be unwrapped.

const
const pattern: RegExp
pattern
= /[\d]/;

The rule also checks regex patterns in RegExp constructor calls.

const
const pattern: RegExp
pattern
= new
var RegExp: RegExpConstructor
new (pattern: RegExp | string, flags?: string) => RegExp (+2 overloads)
RegExp
("[a]");

These cases are valid and will not be reported:

// Negated classes
const
const negated: RegExp
negated
= /[^a]/;
// Backspace escape (has special meaning in character class)
const
const backspace: RegExp
backspace
= /[\b]/;
// Multiple elements
const
const multiple: RegExp
multiple
= /[ab]/;
// Character ranges
const
const range: RegExp
range
= /[a-z]/;
// Equals sign (commonly used in regex for readability)
const
const equals: RegExp
equals
= /[=]/;

This rule is not configurable.

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.

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