False positive for S5665: double slash followed by quote character

Language: Java
Rule: S5665
Why it’s false: I should be able to include a slash character in the string that is followed by a literal quote
Using SonarLint 9.2.0.81471 in Eclipse 4.28.0 (20230608-1333) without connected mode

This java snippet shows TWO instances of a false positive see the embedded “<-” pointing to the cause.

	private static final String S5665_FALSE_POSITIVE_DEMO= """
        This is a path that sonar lint complains about:(single quote):
           'C:\\foo\\bar\\' <- this quote following a slash
        Sonar is fine with this without trailing slash 'C:\\foo\\bar'
        This is another path sonar lint complains about (double quote):  
           "\\\\SERVER\\SHARE\\ETC\\" <- this quote following a slash
        Sonar is also fine with this one: "\\\\SERVER\\SHARE\\ETC"
        But note, the slash is escaping the slash NOT the quote
        """;
1 Like

Hello @mwhaycraft, welcome to the Sonar Community!

Thank you for reaching out and highlighting such cases.

The rule reports an issue any time the \n, \' and \" are found within a text block. This behavior is valid most of the times, although there are cases which the user may intentionally need a backslash before a quote, for example for Windows file paths.

I have created [SONARJAVA-4752] - Jira to not report any issue for Windows file paths, I hope this will be useful for you.

Meanwhile, some workaround may be:

  1. Using String.replace:
String s = 
      """
    path1: '$p1'
    path2: "$p2"
  """
  .replace("$p1", "C:\\foo\\bar\\")
  .replace("$p2",       "\\SERVER\\SHARE\\ETC\\"); 
  1. Using String.formatted:
String s = 
  """
    path1: '%s'
    path2: "%s"
  """.formatted("C:\\foo\\bar\\", "\\SERVER\\SHARE\\ETC\\");
  1. Using String.format:
String s = String.format(
  """
    path1: '%s'
    path2: "%s"
  """,
  "C:\\foo\\bar\\", 
  "\\SERVER\\SHARE\\ETC\\"
);