Java String replaceAll - 以一种奇怪的方式工作

时间:2015-04-15 05:15:17

标签: java string replaceall

我有一个这样的字符串:

My word is "I am busy" message

现在,当我将此字符串分配给pojo字段时,我得到如下转义:

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

我还有一些其他数据,我希望用上面的字符串替换某些内容:

我的基本字符串是:

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

现在我使用replaceAll:

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

这会将输出返回为:

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

为什么在我替换后没有出现“\”。我需要逃避它2次吗?

当它像这样使用时:

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

然后它也提供相同的输出:

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

我的预期输出是:

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

2 个答案:

答案 0 :(得分:4)

试试这个:

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

要获得输出中的\,您需要使用\\\\\

来自docs

  

请注意替换中的反斜杠()和美元符号($)   字符串可能会导致结果与正确的结果不同   被视为字面替换字符串;见Matcher.replaceAll。使用   Matcher.quoteReplacement(java.lang.String)压制特殊   如果需要,这些字符的含义。

所以你可以使用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));

答案 1 :(得分:3)

您需要使用四个反斜杠来打印单个反斜杠。

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

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

<强>输出:

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