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.
Examples
Section titled “Examples”Preceding Quantifier Consumes Characters
Section titled “Preceding Quantifier Consumes Characters”const pattern = /\d+(\d*)/;const pattern = /\d+/;The (\d*) capturing group will always capture the empty string because \d+ already consumed all the digits.
Backtracking End Quantifiers
Section titled “Backtracking End Quantifiers”const pattern = /^(a*).+/;const pattern = /^(a*)(?!a).+/;The (a*) capturing group may capture fewer characters than expected because .+ can force it to give up characters during backtracking.
Redundant Minimum in Capturing Group
Section titled “Redundant Minimum in Capturing Group”const pattern = /a+(a+)/;const pattern = /a+(a)/;The (a+) will always capture exactly one a because all other a characters are consumed by the preceding a+.
Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”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.