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);
}
}
To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')
The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.
You can replace a substring using replace() method in Java. The String class provides the overloaded version of the replace() method, but you need to use the replace(CharSequence target, CharSequence replacement).
The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match. The original string is left unchanged.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With