Regex Unmatchable Boundary
ID |
java.regex_unmatchable_boundary |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
code-style |
Description
Reports a boundary (^, $, \A, \Z, \z) placed next to input that still has to be consumed on the wrong side of it, so the pattern can never match anything.
Rationale
^ and \A can only match at the start of the input; $, \Z and \z only at the end. Swap them, or place one where a character still needs to be matched on the far side, and the pattern becomes impossible to satisfy:
Pattern.compile("$[a-z]+");
// the end boundary is already past the input, so the mandatory
// character class right after it can never get a character to consume
This is usually a typo — ^ and $ swapped, or a boundary left over after editing a pattern — rather than a deliberate choice.
Remediation
Put the boundary on the correct side of what it anchors:
Pattern.compile("^[a-z]+$");
What is not reported
Under MULTILINE, ^ and $ legitimately match mid-pattern at a line break, so this rule stays silent for both there; \A, \Z and \z are unaffected by the flag and are still checked. \b and \B are word boundaries, not input boundaries, and are out of scope. Only the atom immediately adjacent to the boundary is examined — a boundary next to an atom that is itself optional (?, *, {0,n}) is a related but different unmatchable shape and is accepted as a false negative here rather than guessed at.