Paul
Paul

Reputation: 113

replaceAll type method that preserves special characters

Currently, the replaceAll method of the String class, along with Matcher.replaceAll methods evaluate their arguments as regular expressions.

The problem I am having is that the replacement string I am passing to either of these methods contains a dollar sign (which of course has special meaning in a regular expression). An easy work-around to this would be to pass my replacement string to 'Matcher.quoteReplacement' as this produces a string with literal characters, and then pass this sanitized string to replaceAll.

Unfortunately, I can't do the above as I need to preserve the special characters as the resultant string is later used in operations where a reg ex is expected, and if I have escaped all the special characters this will break that contract.

Can someone please suggest a way I might achieve what I want to do? Many thanks.

EDIT: For clearer explanation, please find code example below:

String key = "USD";
String value = "$";

String content = "The figure is in USD";
String contentAfterReplacement;

contentAfterReplacement = content.replaceAll(key, value); //will throw an exception  as it will evaluate the $ in 'value' variable as special regex character

contentAfterReplacement = content.replaceAll(key, Matcher.quoteReplacement(value)); //Can't do this as contentAfterReplacement is passed on and later parsed as a regex (Ie, it can't have special characters escaped).

Upvotes: 1

Views: 270

Answers (1)

anubhava
anubhava

Reputation: 785196

Why not use String#replace method instead of replaceAll. replaceAll uses regex but replace doesn't use regex in replacement string.

Upvotes: 2

Related Questions