In ${fizz}
{
is an indicator to the regex engine that you are about to start a repetition indicator, like {2,4}
which means '2 to 4 times of the previous token'. But {f
is illegal, because it has to be followed by a number, so it throws an exception.
You need to escape all regex metacharacters (in this case $
, {
and }
) (try using http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#quote(java.lang.String) ) or use a different method that substitutes a string for a string, not a regex for a string.
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<String,String> 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;
}
Adapted from Matcher.replaceAll
boolean result = matcher.find();
if (result) {
StringBuffer sb = new StringBuffer();
do {
String tokenKey = matcher.group(1); // Ex: fizz
String replacement = Matcher.quoteReplacement(tokensMap.get(tokenKey));
matcher.appendReplacement(sb, replacement);
result = matcher.find();
} while (result);
matcher.appendTail(sb);
return sb.toString();
}
You can make your RegEx a bit ugly, but this will work
String regex = "\\$[\\{]([^}]*)[\\}]";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With