问题
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