TameHog
TameHog

Reputation: 950

Java replaceAll

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$

Upvotes: 0

Views: 206

Answers (3)

David Conrad
David Conrad

Reputation: 16359

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);

Upvotes: 3

Reimeus
Reimeus

Reputation: 159754

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");

Upvotes: 3

M A
M A

Reputation: 72844

$ 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");

Upvotes: 5

Related Questions