Skip to content

regexUnnecessaryNestedQuantifiers

Reports trivially nested quantifiers in regular expressions that can be simplified.

✅ This rule is included in the ts logical presets.

When a non-capturing group contains a single quantified element and the group itself is quantified, the nested quantifiers can often be combined into a single quantifier. This rule reports trivially nested quantifiers in regular expressions that can be simplified.

(?:a?)+ can be simplified to a* because an optional element repeated one or more times is equivalent to zero or more.

const pattern = /(?:a?)+/;

(?:a+)+ can be simplified to a+ because one or more of one or more is still one or more.

const pattern = /(?:a+)+/;

(?:a+)* can be simplified to a* because one or more repeated zero or more times is zero or more.

const pattern = /(?:a+)*/;

The rule also works with character classes and escape sequences.

const pattern = /(?:[a-z]?)+/;
const digits = /(?:\d+)+/;
const pattern = new RegExp("(?:a?)+");

This rule is not configurable.

If you prefer to keep the nested structure for readability or documentation purposes, or if you need the specific behavior of the non-capturing group for replacement operations, you might prefer to disable this rule. You might consider using Flint disable comments and/or configuration file disables for those specific situations instead of completely disabling this rule.

Made with ❤️‍🔥 in Boston by Josh Goldberg and contributors.