我有一个像这样的字符串:
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
最佳答案
尝试这个:
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));