Search code examples
javastringreplaceall

Java String replaceAll - works in a wierd way for \


I have a string like this :

My word is "I am busy" message

Now when I assign this string to a pojo field, I get is escaped as below :

String test = "My word is \"I am busy\" message";

I have some other data in which I want something to be replaced by above string :

Let say my base string is :

String s = "There is some __data to be replaced here";

Now I when I use replaceAll :

String s1 = s.replaceAll("__data", test);
System.out.println(s1);

This returns me the output as :

There is some My word is "I am busy" message to be replaced here

Why that "\" is not appearing in after I replace. Do I need to escape it 2 times?

Also when use it like this :

String test = "My word is \\\"I am busy\\\" message";

then also it gives the same output as :

There is some My word is "I am busy" message to be replaced here

My expected output is :

There is some My word is \"I am busy\" message to be replaced here

Solution

  • Try this:

    String test = "My word is \\\\\"I am busy\\\\\" message";
    String s = "There is some __data to be replaced here";
    System.out.println(s.replaceAll("__data", test));
    

    To get the \ in your output you need to use \\\\\

    From the docs:

    Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

    So you can use Matcher.quoteReplacement(java.lang.String)

    String test = "My word is \"I am busy\" message";
    String s = "There is some __data to be replaced here";
    System.out.println(s.replaceAll("__data", test), Matcher.quoteReplacement(test));