Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace substring (replaceAll) workaround

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

}
like image 204
user_unknown Avatar asked Nov 05 '10 12:11

user_unknown


People also ask

What can I use instead of replaceAll in JavaScript?

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')

How do you get and replace a substring from a string?

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.

Can you replace substrings in Java?

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

Does replaceAll replace original string?

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.


1 Answers

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

like image 164
kennytm Avatar answered Nov 26 '22 15:11

kennytm