gpt4 book ai didi

Java 替换全部

转载 作者:行者123 更新时间:2023-12-01 06:38:22 26 4
gpt4 key购买 nike

我在使用String.replaceAll(String, String)时发现用$符号替换字符串是行不通的。示例 $REPLACEME$ 在 Linux 系统中不会被替换。有谁知道这是为什么吗?

一些代码:

String foo = "Some string with $REPLACEME$";
foo = foo.replaceAll("$REPLACEME$", "characters");
System.out.println(foo);

输出:

Some string with $REPLACEME$

最佳答案

$ 是需要转义的特殊字符:

foo = foo.replaceAll("\\$REPLACEME\\$", "characters");

或者更一般地使用 Pattern.quote 它将所有元字符(特殊字符,如 $?)转义为字符串文字:

foo = foo.replaceAll(Pattern.quote("$REPLACEME$"), "characters");

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

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