1

My code:

String newBody = response.body.replace(";\"\";", ";\"|||\";");

Where response.body is something like this:

"9.3";"";"";"";"";"";

After the execution it results into this:

"9.3";"|||";"";"|||";"";"|||";

Where I would expect this:

"9.3";"|||";"|||";"|||";"|||";"|||";

I assume it has something to do with the logic of the replacement, as I am taking this: ;""; wanting it to be replaced by this: ;"|||"; while each replaced string is beginning of the new one. But I would still expect it to be handled...

Ondrej Tokar
  • 4,898
  • 8
  • 53
  • 103

3 Answers3

3

In your example the replace method is looking for ;"";. So it will find that starting at the first semicolon. However, after the first time, it then finds "", which it skips, and then finds that pattern again. It is because of your ending semicolon. What you should use is:

String newBody = response.body.replace(";\"\"", ";\"|||\"");
4castle
  • 32,613
  • 11
  • 69
  • 106
mattfred
  • 2,689
  • 1
  • 22
  • 38
  • Thank you for your answer, I have assumed so. The only problem that I haven't used it was that it might happen I will have something like this `;""whateverHere;"";` which would cause issues. – Ondrej Tokar May 24 '16 at 13:24
  • 1
    @mattfred He still needs to use a regex with `g` modifier in order to globally replace, because that will only replace the first `;""`. – lucasarruda May 24 '16 at 13:34
  • 2
    @lucasarruda This is a Java question, not a JavaScript question. – 4castle May 24 '16 at 15:15
2

Change this line :

String newBody = response.body.replace(";\"\";", ";\"|||\";");

To:

String newBody = response.body.replace(";\"\"", ";\"|||\"");
Vucko
  • 7,371
  • 2
  • 27
  • 45
2

To avoid consuming the trailing ; from each match but still check that it is there, use a regex with a look-ahead:

String newBody = response.body.replaceAll(";\"\"(?=;)", ";\"|||\"");
4castle
  • 32,613
  • 11
  • 69
  • 106
  • 1
    Yes, that's better :D. Btw here is proof that your regex works: https://regex101.com/r/hM0tK8/1 – Tom May 24 '16 at 15:42