Skip to content

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.

A backreference inside its own capturing group will always match empty since the group hasn’t finished capturing yet.

const pattern = /(a\1)/;

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)/;

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/;

A backreference to a group inside a negative lookaround will always match empty since the group wasn’t matched.

const pattern = /(?!(a))\w\1/;

In lookbehind assertions, matching proceeds right-to-left, so a backreference after its group is a backward reference.

const pattern = /(?<=(a)\1)b/;

This rule is not configurable.

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.

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