Wrongly suggesting to use .replace() instead of .replaceAll()

Versions

  • Spring Tool Suite 4 Version: 4.11.0.RELEASE Build Id: 202106180608
  • SonarLint for Eclipse 6.0.0.34844
  • Java 8

Error
A hint is created on .replaceAll() calls saying one should use .replace() instead, but those two does not behave the same in Java 8.

Steps/code to reproduce

final String text = "before|inside\\\\/after";
System.out.println(text);
System.out.println(text.replaceAll("\\|", "__").replaceAll("\\/", "__"));
System.out.println(text.replace("\\|", "__").replace("\\/", "__"));

Output

before|inside\\/after
before__inside\\__after
before|inside\__after

Result
After running this simple code one can see output of last two won’t be the same.

Potential workaround
Disable the rule until fixed.

Thanks for reporting this @H.Lo , I’ve forwarded your issue to the relevant team.

1 Like

Hi @H.Lo,

Since the arguments to replace aren’t regular expressions, you shouldn’t use \\ to escape anything in them. Just test.replace("|", "__").replace("/", "__") will do the same thing as the calls to replaceAll, but without the overhead of constructing regular expressions and without the visual clutter of the backslashes.

Though in this particular case where both characters are replaced with the same replacement string, you could instead also use a single call to replaceAll to replace both at the same time:

text.replaceAll("[|/]", "__")

PS: Slashes aren’t special characters in Java regular expressions, so you don’t have to escape them.

Cheers,
Sebastian

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.