Java字符串用求值键替换正则表达式模式
我有一个这样的输入字符串
I want to go to {places} where {things} are happening.
{places}和{things}的值是惰性计算的(即,首先我找出需要替换的所有键,然后计算它们的值,然后在原始字符串中替换它们)
我能够找到所有的钥匙,并删除他们使用下面的代码
public class Temp {
private static final Pattern betweenCurlyBracesMatcher = Pattern.compile("\\{(.*?)\\}");
public static void main(String args[]) {
System.out.println(resolve2("hello {world} from {here}"));
}
public static String resolve2(String input) {
Map<String, String> keyValueMap = new HashMap<>();
Matcher matcher = betweenCurlyBracesMatcher.matcher(input);
while (matcher.find()) {
String key = matcher.group(1);
if (!keyValueMap.containsKey(key)) {
keyValueMap.put(key, computeValueForKey(key));
}
}
for (Map.Entry<String, String> entry : keyValueMap.entrySet()) {
input = input.replace("{" + entry.getKey() + "}", entry.getValue()); // << ugly code here
}
return input;
}
private static String computeValueForKey(String key) {
return "new" + key;
}
}
但我不满意
input = input.replace("{" + entry.getKey() + "}", entry.getValue());
因为这意味着无论何时我改变我的正则表达式,我都必须更新这个逻辑。这个问题有没有更优雅的解决方案
输入你好{world}来自{here}
输出您好,这里是newhere的newworld
输入我想去{地方},那里{事情}正在发生
输出我想去发生新事情的新地方
# 1 楼答案
我们可以用matcher。返回entire matched string的组(0)