I'm trying to replace a String like:
Hello, my name is ${name}. I am ${age} years old.
with
Hello, my name is Johannes. I am 22 years old.
Variables are stored in a HashMap. My code so far:
private void replace() {
HashMap<String, String> replacements = new HashMap<String, String>();
replacements.put("name", "Johannes");
replacements.put("age", "22");
String text = "Hello, my name is {name}. I am {age} years old.";
Pattern pattern = Pattern.compile("\\{(.+?)\\}");
Matcher matcher = pattern.matcher(text);
StringBuilder builder = new StringBuilder();
int i = 0;
while (matcher.find()) {
String replacement = replacements.get(matcher.group(1));
builder.append(text.substring(i, matcher.start()));
if (replacement == null) {
builder.append("");
} else {
builder.append(replacement);
i = matcher.end();
}
}
builder.append(text.substring(i, text.length()));
System.out.println(builder);
}
It's wokring fine, but I would like to replace ${var} and not {var}. Changing it to Pattern.compile("\${(.+?)\}"); will throw an PatternSyntaxException: "Illeagal repetition".
Escaping the $ (Pattern.compile("\\${(.+?)\}") will cause an compiling error.
So How to I have to change my Pattern to accept ${var} instead of {var}
The { character is reserved in most regex libraries for repetition along the lines of {n,m}
. Try the 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