【问题标题】:Adding Escape parameter to a String is not working将 Escape 参数添加到字符串不起作用
【发布时间】:2025-12-26 22:00:11
【问题描述】:

字符串的当前值为

^I am Shaikh with "([^"]*)" and "([^"]*)"$

我的代码如下:

System.out.println(strAnnotationValue); // prints ^I am Shaikh with "([^"]*)" and "([^"]*)"$

strAnnotationValue = strAnnotationValue.replaceAll("\"", "\\\"");
System.out.println(strAnnotationValue); 

Actual Output:   ^I am Shaikh with "([^"]*)" and "([^"]*)"$
Expected Output: ^I am Shaikh with \"([^\"]*)\" and \"([^\"]*)\"$

我已经编写了正确的代码,但它不起作用,还有其他方法可以做到这一点吗?

【问题讨论】:

  • 温馨提示:如果您的代码不起作用,那么您编写的代码很可能不正确。
  • 看看这个答案*.com/questions/20556101/…

标签: java


【解决方案1】:

如果你的代码是完美的,那么你会得到预期的输出吗??

做一件事替换你的这一行

strAnnotationValue = strAnnotationValue.replaceAll("\"", "\\\"");

有了这个

strAnnotationValue = strAnnotationValue.replaceAll("\"", "\\\\\"");

【讨论】:

    【解决方案2】:

    \\\"表示\",输出时显示:"

    这样做:\\\\"

    \\\\"表示\\",输出时为diaplay:\"

    strAnnotationValue = strAnnotationValue.replaceAll("\"", "\\\\\"");
    

    【讨论】:

    • 谢谢你的解释star :)