Friday, May 10, 2013

How to do replaceAll,replaceFirst,... without regular expression

I do love regular expressions, but sometimes you simply want to replace one string with another. And to make things worse, sometimes your search string is unknown during development time, so it would be great somehow to tell Java not to try parsing search string as a regular expression. For that, I found the best way is the following:

String newString = oldString.replaceAll(Pattern.quote(searchString),replacementString);

Additionally, this way you ensure no bugs in case your pure text-based searchString not to become compilable regular expression, which can surprisingly often be the main source of bugs :)