Replace Substitution Method (replaceAll)

I am trying to replace a substring containing char "$". I would be glad to hear why it does not work like this and how it will 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);
    }

}
+5
source share
4 answers

Java.replaceAll implicitly uses Regex for replacement. This means that it is $foointerpreted as a regular expression pattern, and $is special in the regular expression (which means "end of line").

You need to avoid $how

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

, Pattern.quote Java β‰₯1.5, , Matcher.quoteReplacement.

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

Java β‰₯1.5 .replace .

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

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

+14

Regex, regex.

String.replace(str, str):

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

:

+9

IIRC, replaceAll, take the regex: try to avoid $, this way:

String s3 = s2.replaceAll("\\$foo", "damn");
+5
source
public static String safeReplaceAll(String orig, String target, String replacement) {
    replacement = replacement.replace("$", "\\$");
    return orig.replaceAll(target, replacement);
}
0
source

All Articles