Avoid Literal "." In Regex String Methods

ID

java.string_regex_literal_dot

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

code-style

Description

Reports calls to String.split, String.replaceAll, and String.replaceFirst whose first argument is the string literal ".".

Rationale

These three String methods interpret their first argument as a regular expression, not as a plain string. In regex syntax . matches any character, so passing the literal "." almost never does what the author intended. For instance:

"a.b.c".split(".")       // returns String[0] — every char is eaten
"abc".replaceAll(".", "X")   // returns "XXX", not "abc"

The bug usually hides behind the assumption that "." is the separator character. Escaping it ("\\.") makes the regex semantics explicit; using a non-regex alternative (String.replace(CharSequence, CharSequence)) sidesteps the interpretation entirely.

// Bad — '.' in a regex matches any character
String[] parts = hostname.split(".");

// Good — escape the dot so it matches literally
String[] parts = hostname.split("\\.");

// Good — String.replace(CharSequence, CharSequence) is not regex-based
String cleaned = text.replace(".", "_");

Remediation

When the first argument is a plain string and the regex power is not needed, call String.replace(CharSequence, CharSequence) instead. When regex is required, escape the dot as \\. (or wrap the whole pattern with Pattern.quote(…​) when the separator is computed at runtime).