1

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
Abubakkar
  • 15,488
  • 8
  • 55
  • 83

2 Answers2

4

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));
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • I don't have control over adding backslash, I am getting the data from outside. Do you mean I escape it twice? – Abubakkar Apr 15 '15 at 05:22
3

You need to use four backslashes to print a single backslash.

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));

OR

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.replace("\"", "\\\\\"")));

Output:

There is some My word is \"I am busy\" message to be replaced here
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • I don't have control over adding backslash, I am getting the data from outside. Do you mean I escape it twice? – Abubakkar Apr 15 '15 at 05:22