0

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$
M A
73.2k14 gold badges150 silver badges182 bronze badges
asked Oct 8, 2014 at 20:23
1
  • 2
    Why are you using replaceAll rather than replace? Do you need regular expressions? Commented Oct 8, 2014 at 20:30

3 Answers 3

5

$ 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");
answered Oct 8, 2014 at 20:24
Sign up to request clarification or add additional context in comments.

4 Comments

Why does it need to be escaped?
It means end of a line in regular expression syntax. So unless you have an end of string at the start of your string...
+1 for Pattern.quote, I was already contemplating an answer.
Thanks for the Pattern.quote
3

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");
answered Oct 8, 2014 at 20:24

1 Comment

I would also add that in pure regex, a literal dollar sign has to be escaped \$, but in Java the escape character has to be escaped, hence \\$.
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);
answered Oct 8, 2014 at 20:33

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.