Pattern.compile In Loop

ID

java.pattern_compile_loop

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Efficiency

Language

Java

Tags

efficiency

Description

Reports Pattern.compile(…​) calls executed inside a loop body.

Rationale

Pattern.compile builds the NFA for the regular expression. Doing it once per loop iteration multiplies compilation work for no gain, since the resulting Pattern is immutable and thread-safe — it can safely be hoisted out of the loop (or stored as a static final field).

// Bad — recompiles on every iteration
for (String input : inputs) {
    Pattern p = Pattern.compile("\\d+");
    p.matcher(input).find();
}

// Good — compile once
private static final Pattern P = Pattern.compile("\\d+");

void run(List<String> inputs) {
    for (String input : inputs) {
        P.matcher(input).find();
    }
}

Remediation

Hoist the Pattern.compile call out of the loop, or move the pattern to a private static final field.