Search code examples
javastringsonarcloud

Java string.replace not working as string.replaceAll


I have an entry coming from database in the below format. I first used replaceAll instead of replace function but SonarCloud show error and asks to change from replaceAll to replace. However, the replace dosen't replace all the backslash, infact it does not change anything in the text.

Entry from database in java code:

""{\"id\":\"5947223f-9c50-425f-950b-e126c94b3adf\",\"name\":\"shruti\"}

With replaceAll I wrote code as below which works fine:

abcString.replaceAll("\\\\", "").replaceFirst("\"","");

To make SonarCloud happy, I try to change replaceAll with replace which in turn tell be to remove replaceFirst method otherwise it removes the both the double quotes from the database output.

Code with replace function:

abcString.replace("\\\\", "")

The second thing that I tried gives error:

Unexpected character ('\' (code 92)): was expecting double-quote to start field name
!  at [Source: (String)"{\"id\":\"5947223f-9c50-425f-950b-e126c94b3adf\",\"name\":\"shruti\"}

Solution

  • Your real problem

    JSON isn't regular at all, you can't just go messing with it like this. You should use a real JSON parser, and whatever gave you this backslashified monstrosity is where the real bug lies. The problem you're facing here can be 'fixed', but your code will remain a fragile mess until you fix this underlying problem!

    Your approach to SonarCloud

    You shouldn't be using tools like this unless you understand what they do, and given that you ask this question with no idea as to why SonarCloud is even suggesting you replace replaceAll to replace, that sounds like this advice applies to you. Always read the reasoning behind a linting rule.

    The problem

    .replaceAll replaces each occurrence, but is regular expression based. .replace replaces each occurrence, and isn't - it just replaces the literal string you write. So, all you need to do is .replace("\\", ""). The replaceAll requires 4 backslashes, because that becomes a string with 2 backslashes, which is regexp-ese for '1 backslash'.