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