Replace substring (replaceAll) workaround
Asked Answered
J

4

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

}
Jolley answered 5/11, 2010 at 12:30 Comment(2)
And what does this print out? $foo - this works - bla?Progestational
possible duplicate of Backslash problem with String.replaceAllGreenlet
P
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

Prickett answered 5/11, 2010 at 12:33 Comment(2)
Very good answer, but IMHO you are solving the wrong problem.Tortricid
Also note that replacement string for replaceAll() may need escaping too (with Pattern.quoteReplacement()).Bunnie
T
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:

Tortricid answered 5/11, 2010 at 12:37 Comment(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)Zoubek
I
5

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

String s3 = s2.replaceAll("\\$foo", "damn");
Infatuated answered 5/11, 2010 at 12:32 Comment(0)
B
0
public static String safeReplaceAll(String orig, String target, String replacement) {
    replacement = replacement.replace("$", "\\$");
    return orig.replaceAll(target, replacement);
}
Beauregard answered 1/3, 2012 at 17:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.