Java String replaceAll - 以奇怪的方式为 \

Java String replaceAll - works in a wierd way for \

我有这样的字符串:

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

这 returns 我的输出为:

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

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

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

试试这个:

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

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.

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