Back reference in a regular expression should be used after the referred group
- BAD_BACK_REFERENCE_IN_REGEXP
- Error
- Medium
- No tags
This rule applies when a back reference in a regular expression is used before the referred group matches.
A back reference like \1
is used to refer the input characters previously matched by a capture group. For example, /(foo|bar)\1/
will match foofoo
or barbar
but not foobar
.
However, when a back reference is placed before the referred group, it will always match just the empty string. This is not likely to be a programmer's intent.
Noncompliant Code Example
View with compliant examples side by sidevar re = /\1(foo|bar)/; // BAD_BACK_REFERENCE_IN_REGEXP alarm because the referred group '(foo|bar)` appears after the reference '\1'.
Compliant Code Example
View with noncompliant examples side by sidevar re = /(foo|bar)\1/;
Version
This rule was introduced in DeepScan 1.30.0.