I you want to replace only the words that you have in the map and keep the rest as it is, you can proceed as next:
String template = "Hey {how} are $=you";
StringBuilder populatedTemplate = new StringBuilder();
Map<String, String> map = new HashMap<>();
map.put("how", "HH");
map.put("you", "YY");
// Pattern allowing to extract only the words
Pattern pattern = Pattern.compile("\\w+");
Matcher matcher = pattern.matcher(template);
int fromIndex = 0;
while (matcher.find(fromIndex)) {
// The start index of the current word
int startIdx = matcher.start();
if (fromIndex < startIdx) {
// Add what we have between two words
populatedTemplate.append(template, fromIndex, startIdx);
}
// The current word
String word = matcher.group();
// Replace the word by itself or what we have in the map
populatedTemplate.append(map.getOrDefault(word, word));
// Start the next find from the end index of the current word
fromIndex = matcher.end();
}
if (fromIndex < template.length()) {
// Add the remaining sub String
populatedTemplate.append(template, fromIndex, template.length());
}
System.out.println(populatedTemplate);
Output:
Hey {HH} are $=YY
Response Update:
Assuming that you want to be able to replace not only words but anything like ${questionNumber}
, you will need to create the regular expression dynamically like this:
String template = "Hey {how} are $=you id=minScaleBox-${questionNumber}";
...
map.put("${questionNumber}", "foo");
StringBuilder regex = new StringBuilder();
boolean first = true;
for (String word : map.keySet()) {
if (first) {
first = false;
} else {
regex.append('|');
}
regex.append(Pattern.quote(word));
}
Pattern pattern = Pattern.compile(regex.toString());
...
Output:
Hey {HH} are $=YY id=minScaleBox-foo