问题描述
我正在尝试替换类似的字符串:
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.
变量存储在HashMap中。
到目前为止我的代码:
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);
}
这很好,但是我想替换$ {var}而不是{VAR}。
将其更改为Pattern.compile(\ $ {(。+?)\});将抛出PatternSyntaxException:Illeagal重复。
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".
转义$(Pattern.compile(\\ $ {(。+?)\})将导致编译错误。
Escaping the $ (Pattern.compile("\\${(.+?)\}") will cause an compiling error.
所以如何更改我的模式以接受$ {var}而不是{var}
推荐答案
在大多数正则表达式库中保留{字符,以便在 {n,m}
的行中重复。尝试正则表达式
The { character is reserved in most regex libraries for repetition along the lines of {n,m}
. Try the regex
\\$\\{(.+?)\\}
这篇关于java正则表达式:替换$ {var}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!