Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

359
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda