gpt4 book ai didi

java - 用\$转义$

转载 作者:行者123 更新时间:2023-12-01 18:03:15 30 4
gpt4 key购买 nike

我需要转义 $,因此我需要将所有出现的 $ 替换为 \$

所以我写了这个方法:

// String#replaceAll(String regex, String replacement)
public String escape$(String str) {
// the first \\$ to escape it in regular expression
// the second is a normal String so \\$ should mean \$
return str.replaceAll("\\$", "\\$");
}


String s = "$some$$text here";
System.out.println(escape$(s));

在我提交用于生产用途之前,我想嗯,让我们测试一下,尽管我确信它应该可以工作。于是我就这么做了...

好吧,你猜对了。这不起作用!它返回相同的东西!

// expected result of the above: \$some\$\$text here
// reality: $some$$text here

那么为什么这不起作用?!

最佳答案

您需要对替换内容进行双重转义。

您可能不想使用 replaceAll,因为您实际上需要对它进行双倍转义,但这里没有使用正则表达式。

相反,您可以只使用 replace,它接受文字(并在后台使用 replaceAll,带引号的值 - 请参阅 Matcher#quoteReplacement )。

这里有两个例子:

System.out.println("$".replaceAll("\\$", "\\\\\\$"));
System.out.println("$".replace("$", "\\$"));

输出

\$
\$

关于java - 用\$转义$,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39000783/

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