Regex Empty Line Under Multiline

ID

java.regex_empty_line_multiline

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

code-style

Description

Reports a regex compiled with MULTILINE whose pattern is exactly ^$ — a common way to test for an empty line that quietly fails on a completely empty input.

Rationale

Under MULTILINE, ^ matches at the start of input and right after any line terminator, but never at the very end of input; $ matches right before a line terminator or at the end of input. An empty string is entirely "end of input", so ^$ never gets to match it:

Pattern p = Pattern.compile("^$", Pattern.MULTILINE);

p.matcher("a\n\nb").find(); // true - correctly finds the empty line
p.matcher("").find();       // false - the empty string itself is missed

Anything that relies on ^$ alone to detect "this is blank" silently gets the wrong answer for the one input that is entirely blank.

Remediation

Check isEmpty() alongside the regex match:

boolean hasEmptyLine(String text) {
  return p.matcher(text).find() || text.isEmpty();
}

What is not reported

This rule fires at the compile call itself and does not try to trace whether the resulting Pattern is later used with find() — tracking that across statements risks a wrong correlation, which would be a worse failure mode than a pattern that is compiled this way but never searched. A ^$ pattern assigned to a field is not reported, since a field’s own declaration line rarely reflects how it is used. A pattern other than exactly ^$, or one compiled without MULTILINE (in the flags argument or as an inline (?m)), is not reported either.

© 2026 Xygeni. All rights reserved