OmegaDelta.net

Hong Kong

Simple Java ReplaceAll for string literals (i.e. no regex)

Regex is great.  Really great.  But sometimes you just don’t want it.  Java provides a Stirng.replaceAll method but it uses regex and both parameters MUST be escaped if you just want a string literal replace.

Use Pattern.quote for the first param of Stirng.replaceAll, and Matcher.quoteReplacement for the second.

Here’s an example on how to escape the regex parameters:

String myString = “foo[]bar”;
myString = myString.replaceAll(Pattern.quote(“foo[]“), Matcher.quoteReplacement(“bar$”));
System.out.println(myString);
// output bar$bar

If you don’t believe me, try the above sample with

myString = myString.replaceAll(“foo[]“, “bar$”);

(you will get exceptions for both arguments if you try).

Hope that helped…

Leave a Reply