Invalid Regex Back-Reference
ID |
java.back_references_regular_expr_refer |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
reliability |
Description
Reports a regex back-reference (\1, \k<name>) that points at a capturing group that does not exist in the pattern, or that is not yet fully defined at the point the back-reference appears.
Rationale
java.util.regex compiles a back-reference to a non-existent or not-yet-closed group without complaint, but the back-reference can never match anything: the group it points at has not captured a value yet.
Pattern.compile("(\\1)"); // self-reference: group 1 back-references itself
Pattern.compile("\\1(a)"); // forward reference: \1 appears before group 1 even opens
Pattern.compile("(a)\\2"); // \2 does not exist -- there is only one group
Remediation
Reference a group that is already closed by the time the back-reference is reached, and make sure the group number or name actually exists in the pattern:
Pattern.compile("(a)\\1"); // valid: group 1 is closed before \1
Pattern.compile("(?<word>\\w+)\\s+\\k<word>"); // valid named back-reference