Skip to content

regexMisleadingCapturingGroups

Reports capturing groups that capture less text than their pattern suggests.

✅ This rule is included in the ts logical presets.

Reports capturing groups that capture less text than their pattern suggests. This happens when a quantifier in a capturing group matches the same characters as a preceding quantifier, causing the capturing group to always capture less than expected.

const pattern = /\d+(\d*)/;

The (\d*) capturing group will always capture the empty string because \d+ already consumed all the digits.

const pattern = /^(a*).+/;

The (a*) capturing group may capture fewer characters than expected because .+ can force it to give up characters during backtracking.

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

The (a+) will always capture exactly one a because all other a characters are consumed by the preceding a+.

This rule is not configurable.

If the behavior of capturing less text is intentional, or if you are working with patterns where the capturing group is only used for backreferences and the exact captured content is not important, you might want to disable this rule.

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