Redundant Regex Alternation Branch
ID |
java.regex_alternatives_redundant |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Code Smell |
Language |
Java |
Tags |
code-style |
Description
Reports an alternation branch that can never match anything another branch of the same alternation does not already match, restricted to three shapes that do not need a general regex-subsumption engine to decide: two identical literal branches, a single character already covered by a sibling character class, and any branch alongside a sibling .*/.+, which matches everything.
Rationale
A branch that only matches what another branch already matches serves no purpose:
"[ab]|a" // "|a" is redundant - "[ab]" already matches "a"
".*|a" // ".*" matches everything, so "a" never gets to add anything
"ab|ab" // the same literal, twice
In the best case it is dead weight; in the worst case it is a sign the pattern does not match what the author intended and should be reworked.
Remediation
Drop the redundant branch:
"[ab]"
".*"
"ab"
What is not reported
This rule deliberately covers only the three shapes above. General subsumption — deciding whether one arbitrary subpattern’s matches are a subset of another’s — is not attempted, because a wrong verdict would delete a branch the author needed; genuinely disjoint branches, and anything wider than the three shapes, are accepted as false negatives rather than guessed at. A redundant-looking branch inside its own capturing group is not reported either — the group is what tells the caller which alternative actually matched, so it is still doing useful work.