user1955000
user1955000

Reputation: 11

Replacing a variable with a value in Java

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.

Upvotes: 1

Views: 11530

Answers (2)

Manuel Miranda
Manuel Miranda

Reputation: 823

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"

Upvotes: 2

Audrius Meškauskas
Audrius Meškauskas

Reputation: 21748

String.replaceAll() takes a regular expression as a parameter, and $ has a special meaning there. Just escape dollar signs with \:

myString.replaceAll("\\$variable\\$", replacement);

Upvotes: 2

Related Questions