regexUnnecessaryBackreferences
Reports backreferences in regular expressions that will always match empty or fail.
✅ This rule is included in the ts logical presets.
Reports backreferences in regular expressions that will always match empty or fail to match. These backreferences are useless because they reference capturing groups that haven’t captured anything at the time the backreference is evaluated.
Examples
Section titled “Examples”Nested Backreference
Section titled “Nested Backreference”A backreference inside its own capturing group will always match empty since the group hasn’t finished capturing yet.
const pattern = /(a\1)/;const pattern = /(a)\1/;Forward Reference
Section titled “Forward Reference”A backreference that appears before the group it references will always match empty since the group hasn’t been matched yet.
const pattern = /\1(a)/;const pattern = /(a)\1/;Disjunctive Backreference
Section titled “Disjunctive Backreference”A backreference in a different alternative from its group will always match empty since the group’s alternative wasn’t taken.
const pattern = /(a)|\1/;const pattern = /(a)\1|b/;Negative Lookaround
Section titled “Negative Lookaround”A backreference to a group inside a negative lookaround will always match empty since the group wasn’t matched.
const pattern = /(?!(a))\w\1/;const pattern = /(?=(a))\w\1/;Lookbehind Direction
Section titled “Lookbehind Direction”In lookbehind assertions, matching proceeds right-to-left, so a backreference after its group is a backward reference.
const pattern = /(?<=(a)\1)b/;const pattern = /(?<=\1(a))b/;Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If you are intentionally using backreferences that match empty strings for specific pattern-matching logic, you might want to disable this rule. However, in most cases, these patterns indicate a mistake in the regular expression.