1

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.

2 Answers 2

2

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

myString.replaceAll("\\$variable\\$", replacement);
Sign up to request clarification or add additional context in comments.

Comments

2

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

This will not compile as String.replace takes a char only and not a string.
Are you sure? public String replace(CharSequence target, CharSequence replacement). please, check the API before downvoting.
Some of these new methods that older generation does not recall and never use. Consider linking. Upvoting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.