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

Comments

Anonymous said…
This comment has been removed by a blog administrator.

Popular posts from this blog

Timeline on Latex

Exporting Skype Chat/Skype Contacts to csv file using the shell script and sqlite3 (usually already installed on mac)

trim() not supported by IE7 and IE8