I have a string that has certain variables like "This is string containing $variable$". I want to replace this $variable$ with a new string. If I use replaceall method like str.replaceall("$variable$","new_value") it is not getting replaced. But if I give without $ symbols, it is replacing. But my output is like this, $new_value$.
I need it without the $ symbol.
Add a comment
|
2 Answers
String.replaceAll() takes a regular expression as a parameter, and $ has a special meaning there. Just escape dollar signs with \:
myString.replaceAll("\\$variable\\$", replacement);
Comments
Try to use String.replace(CharSequence, CharSequence):
str.replace("$variable$","new_value");
because String.replaceAll() expects a regular expression as the first parameter, and the $ character on regular expression stands for "match at the end of the string"
3 Comments
Audrius Meškauskas
This will not compile as String.replace takes a char only and not a string.
Manuel Miranda
Are you sure? public String replace(CharSequence target, CharSequence replacement). please, check the API before downvoting.
Audrius Meškauskas
Some of these new methods that older generation does not recall and never use. Consider linking. Upvoting.