5

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

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

}
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
user_unknown
  • 195
  • 2
  • 4
  • 7
  • And what does this print out? `$foo - this works - bla`? – Entity Nov 05 '10 at 12:32
  • possible duplicate of [Backslash problem with String.replaceAll](http://stackoverflow.com/questions/1701839/backslash-problem-with-string-replaceall) – McDowell May 26 '11 at 08:37

4 Answers4

14

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

You need to escape the $ 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.

String s3 = s2.replaceAll(Pattern.quote("$foo"), Matcher.quoteReplacement("damn"));

On Java ≥1.5, you could use .replace instead.

String s3 = s2.replace("$foo", "damn");

Result: http://www.ideone.com/Jm2c4

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
9

If you don't need Regex functionality, don't use the regex version.

Use String.replace(str, str) instead:

String s = "$$$";
String rep = s.replace("$", "€");
System.out.println(rep);
// Output: €€€

Reference:

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • 1
    +1 - I'd accepted this answer. replaceAll is for replacing matches of a pattern, replace for char sequence substitution (which is exactly what we want here) – Andreas Dolk Nov 05 '10 at 12:55
5

IIRC, replaceAll take a regex : Try to escape the $, this way :

String s3 = s2.replaceAll("\\$foo", "damn");
blue112
  • 52,634
  • 3
  • 45
  • 54
0
public static String safeReplaceAll(String orig, String target, String replacement) {
    replacement = replacement.replace("$", "\\$");
    return orig.replaceAll(target, replacement);
}
Zip184
  • 1,792
  • 2
  • 21
  • 34