I am trying to write a method that will accept a String, inspect it for instances of certain tokens (e.g. ${fizz}, ${buzz}, ${fo
As pointed out by Patashu, the problem is in replaceFirst(token, replacementValue), that expects a regex in the first argument, not a literal. Change it to replaceFirst(Pattern.quote(token), replacementValue) and you will do alright.
I also changed a bit the first regex, as it goes faster with + instead of * but that's not necessary.
static String substituteAllTokens(Map tokensMap, String toInspect) {
String regex = "\\$\\{([^}]+)\\}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(toInspect);
String result = toInspect;
while(matcher.find()) {
String token = matcher.group(); // Ex: ${fizz}
String tokenKey = matcher.group(1); // Ex: fizz
String replacementValue = null;
if(tokensMap.containsKey(tokenKey))
replacementValue = tokensMap.get(tokenKey);
else
throw new RuntimeException("String contained an unsupported token.");
result = result.replaceFirst(Pattern.quote(token), replacementValue);
}
return result;
}