java 替换子字符串 (replaceAll) 解决方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4105843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace substring (replaceAll) workaround
提问by user_unknown
I'm trying to replace a substring that contains the char "$". I'd be glad to hear why it didnt works that way, and how it would work.
我正在尝试替换包含字符“$”的子字符串。我很高兴听到为什么它不能那样工作,以及它是如何工作的。
Thanks, user_unknown
谢谢,user_unknown
public class replaceall {
public static void main(String args[]) {
String s1= "$foo - bar - bla";
System.out.println("Original string:\n"+s1);
String s2 = s1.replaceAll("bar", "this works");
System.out.println("new String:\n"+s2);
String s3 = s2.replaceAll("$foo", "damn");
System.out.println("new String:\n"+s3);
}
}
回答by kennytm
Java's .replaceAll
implicitly uses Regex to replace. That means, $foo
is interpreted as a regex pattern, and $
is special in regex (meaning "end of string").
Java 的.replaceAll
隐式使用 Regex 来替换。这意味着,$foo
被解释为正则表达式模式,并且$
在正则表达式中是特殊的(意思是“字符串结尾”)。
You need to escape the $
as
你需要逃避$
as
String s3 = s2.replaceAll("\$foo", "damn");
if the target a variable, use Pattern.quote
to escape all special characters on Java ≥1.5, and if the replacement is also a variable, use Matcher.quoteReplacement
.
如果目标是变量,则使用Pattern.quote
转义 Java ≥1.5 上的所有特殊字符,如果替换也是变量,则使用Matcher.quoteReplacement
.
String s3 = s2.replaceAll(Pattern.quote("$foo"), Matcher.quoteReplacement("damn"));
On Java ≥1.5, you could use .replace
instead.
关于Java≥1.5,你可以使用.replace
代替。
String s3 = s2.replace("$foo", "damn");
Result: http://www.ideone.com/Jm2c4
回答by Sean Patrick Floyd
If you don't need Regex functionality, don't use the regex version.
如果您不需要正则表达式功能,请不要使用正则表达式版本。
Use String.replace(str, str)
instead:
使用String.replace(str, str)
来代替:
String s = "$$$";
String rep = s.replace("$", "");
System.out.println(rep);
// Output:
Reference:
参考:
回答by blue112
IIRC, replaceAll take a regex : Try to escape the $, this way :
IIRC,replaceAll 使用正则表达式:尝试转义 $,这样:
String s3 = s2.replaceAll("\$foo", "damn");
回答by Zip184
public static String safeReplaceAll(String orig, String target, String replacement) {
replacement = replacement.replace("$", "\$");
return orig.replaceAll(target, replacement);
}