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
anindyaju99
5751 gold badge5 silver badges16 bronze badges
-
Start by reading. Then move to trying. When you get stuck, give us a specific example. Good luck.james.garriss– james.garriss2013年12月23日 13:50:34 +00:00Commented Dec 23, 2013 at 13:50
3 Answers 3
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
Sachin
3,5944 gold badges25 silver badges45 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
Alexey Odintsov
1,72512 silver badges13 bronze badges
Comments
This type of question has already been asked at SO. you need to see THIS.
answered Dec 23, 2013 at 8:11
Zeeshan
3,0243 gold badges30 silver badges48 bronze badges
1 Comment
anindyaju99
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.
lang-java