Search code examples
javareplaceall

replaceAll pastes part of unnecessary extra string


This is my example java code:

String oldContent = "Book 1;Author 1;11|11\n" +
        "Book 2;Author 2;1|1\n" +
        "Book 3;Author 3;1|1\n" +
        "Book 4;Author 4;1|1\n" +
        "Book 5;Author 5;1|1\n";

String old = "Book 1;Author 1;11";
String newS = "Book 1;Author 1;12|12";

String content = oldContent.replace(old,newS);

System.out.println(content);

I'm trying to update part of String in oldContent (old) with new part of string (newS). The result should be:

Book 1;Author 1;12|12
Book 2;Author 2;1|1
Book 3;Author 3;1|1
Book 4;Author 4;1|1
Book 5;Author 5;1|1

but actually is:

Book 1;Author 1;12|12|11
Book 2;Author 2;1|1
Book 3;Author 3;1|1
Book 4;Author 4;1|1
Book 5;Author 5;1|1

with these extra |11 . Could someone explain me how it works and why? I have been trying with replace(), replaceAll() but result is the same.


Solution

  • You are replacing Book 1;Author 1;11|11 sequence with Book 1;Autor 1;12|12 sequence however the first line ends with 1:11|11. Notice the extra |11 at the end of a line, it won't be processed and will be appended to Book 1;Autor 1;12|12.

    To fully replace first line you need:

    String old = "Book 1;Autor 1;11|11";
    String newS = "Book 1;Autor 1;12|12";
    String content = oldContent.replace(old, newS);