【问题标题】:Java String replaceAll - works in a wierd way for \Java String replaceAll - 以奇怪的方式工作 \
【发布时间】:2015-04-15 05:15:17
【问题描述】:

我有一个这样的字符串:

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

【问题讨论】:

标签: java string replaceall


【解决方案1】:

试试这个:

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

【讨论】:

  • 我无法控制添加反斜杠,我是从外部获取数据。你的意思是我逃脱了两次?
【解决方案2】:

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

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

【讨论】:

  • 我无法控制添加反斜杠,我是从外部获取数据。你的意思是我逃脱了两次?
猜你喜欢
  • 1970-01-01
  • 2017-09-02
  • 1970-01-01
  • 2019-08-03
  • 2020-12-25
  • 2011-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多