Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

358
Vistas
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\"}
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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'.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda