I am trying to write a method that will accept a String
, inspect it for instances of certain tokens (e.g. ${fizz}
, ${buzz}
, ${foo}
, etc.) and replace each token with a new string that is fetched from a Map<String,String>
.
For example, if I pass this method the following string:
"How now ${fizz} cow. The ${buzz} had oddly-shaped ${foo}."
And if the method consulted the following Map<String,String>
:
Key Value
==========================
"fizz" "brown"
"buzz" "arsonist"
"foo" "feet"
Then the resultant string would be:
"How now brown cow. The arsonist had oddly-shaped feet."
Here is my method:
String substituteAllTokens(Map<String,String> tokensMap, String toInspect) {
String regex = "\\$\\{([^}]*)\\}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(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.");
toInspect = toInspect.replaceFirst(token, replacementValue);
}
return toInspect;
}
When I run this, I get the following exception:
Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 0
${fizz}
^
at java.util.regex.Pattern.error(Pattern.java:1730)
at java.util.regex.Pattern.closure(Pattern.java:2792)
at java.util.regex.Pattern.sequence(Pattern.java:1906)
at java.util.regex.Pattern.expr(Pattern.java:1769)
at java.util.regex.Pattern.compile(Pattern.java:1477)
at java.util.regex.Pattern.<init>(Pattern.java:1150)
at java.util.regex.Pattern.compile(Pattern.java:840)
at java.lang.String.replaceFirst(String.java:2158)
...rest of stack trace omitted for brevity (but available upon request!)
Why am I getting this? And what is the correct fix? Thanks in advance!