gpt4 book ai didi

Java 替换 "with\"

转载 作者:行者123 更新时间:2023-11-29 09:55:37 29 4
gpt4 key购买 nike

我正在尝试用\"替换包含 "的字符串,下面是我尝试过的程序

    String s="\"/test /string\"";
s = s.replaceAll("\"", "\\\"");
System.out.println(s);

但我得到与字符串“/test/string”相同的输出。为什么我的替换功能不起作用。如果我这样做

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

然后我得到我想要的输出\"/test/string\"。为什么以前的 dint 有效,即使在代码中我试图用\"替换“

最佳答案

您正在使用 String.replaceAll ,它以正则表达式作为输入,包括替换。如 Match.replaceAll() 中所述:

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.

你真的只是想做一个不涉及正则表达式的直接替换,所以使用 String.replace相反:

s = s.replace("\"", "\\\"");

关于Java 替换 "with\",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12815891/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com