0

I have a string like "${f1}:blah blah ${f2} blah ${f1}". I have a Map<String, String> with "f1", "f2" as the keys.

I want to replace "${f1}", "${f2}" etc in the string with the corresponding values given in the map.

How do I do that in Java? I have hardly any experience with Java regex.

falsetru
371k69 gold badges770 silver badges660 bronze badges
asked Dec 23, 2013 at 8:04
1
  • Start by reading. Then move to trying. When you get stuck, give us a specific example. Good luck. Commented Dec 23, 2013 at 13:50

3 Answers 3

0

try this one

for (Entry<String, String> e : map.entrySet()) {
 String test="${f1}:blah blah ${f2} blah ${f1}";
 System.out.println(test.replace("${f2}", e.getValue()).replace("${f1}", e.getKey()));
 }
answered Dec 23, 2013 at 8:10
Sign up to request clarification or add additional context in comments.

Comments

0

You may do it this way

 String str = "${f1}:blah blah ${f2} blah ${f1}";
 Map<String, String> map = new HashMap<String, String>();
 map.put("\\$\\{f1\\}", "xxxx");
 map.put("\\$\\{f2\\}", "yyyy");
 for (Map.Entry entry: map.entrySet()) {
 str = str.replaceAll((String)entry.getKey(), (String)entry.getValue());
 }
 System.out.println(str);

The output is:

xxxx:blah blah yyyy blah xxxx
answered Dec 23, 2013 at 8:13

Comments

-2

This type of question has already been asked at SO. you need to see THIS.

answered Dec 23, 2013 at 8:11

1 Comment

The others suggested a loop with replacement. That seems like too expensive. This link on the other hand finds out all the ${f1} ${f2} etc and replace them accordingly. So you don't end up traversing the same string multiple times.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.