mardi 31 mars 2015

most elegant way of escaping $ in java

I have a base String "abc def", I am trying to replace my base string with "abc$ def$" using replaceFirst() method, which is running into errors as $ is not escaped.


I tried doing it with Pattern and Matcher APIs, as given below,


newValue = "abc$ def$";


if(newValue.contains("$")){


Pattern specialCharacters = Pattern.compile("$");


Matcher newMatcherValue = specialCharacters.matcher(newValue) ;


newValue = newMatcherValue.replaceAll("\\$") ;

}


This runs into error. Is there any elegant way of replacing my second string "abc$ def$" with "abc\\$ def\\$".so as to use the replacefirst() API successfully.


Thanks in Advance.


Aucun commentaire:

Enregistrer un commentaire