Java replaceAll

谁说我不能喝 提交于 2019-12-11 20:34:40

问题


I was using String.replaceAll(String, String) when I noticed that replacing a string with $ symbols around it would not work. Example $REPLACEME$ would not be replaced in a Linux system. Anyone know why this is?

Some code:

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

Output:

Some string with $REPLACEME$

回答1:


$ is a special character that needs to be escaped:

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

Or more generally use Pattern.quote which will escape all metacharacters (special characters like $ and ?) into string literals:

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



回答2:


replaceAll uses a regular expression as its first argument. $ is an anchor character that matches the end of a matching string in regex so needs to be escaped

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



回答3:


The replaceAll method uses regular expressions, and the $ character is a metacharacter in a regular expression that represents the end of the string. However, the replace method also replaces all instances of the target string with the replacement string, and uses an ordinary string, not a regular expression. This will do what you are expecting:

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


来源:https://stackoverflow.com/questions/26265752/java-replaceall

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!