how to replace special characters in a String

Hi guys

I have a while loop in which I am trying to replace "${"+key+"}" with a value in a String. But somehow it throws a parsing exception. Would anyone know if there is another way to replace special characters from a String.

                  String key = (String)enum.nextElement();
                  String value = (String)hshParams.get(key);
                  strSearch = strSearch.replaceAll("${"+key+"}", value);

Anyhelp will be greatly appreciated
Who is Participating?
CEHJConnect With a Mentor Commented:

strSearch = strSearch.replaceAll("\\$\\{"+key+"\\}", value);
huzefaqAuthor Commented:
Thanks CEHJ

can you please explain what does the code do. why did you surrounded $ with \\ and also put it after key

It's escaping any reserved regex characters
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

objectsConnect With a Mentor Commented:
$ { and } have special significance in a regex string. So you need to escape them.
You're also going to have problems if your key or value contain any special characters
objectsConnect With a Mentor Commented:
be easier (and a lot more powerful) to use a templating library.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.