![](/img/trans.png)
[英]how to replace all occurences of a word in a string with another word in java?
[英]Java - Replace all occurences of '${' in string
我正在使用 Java 1.8 来迭代包含这样定义的变量的文件。
<var name = "QUEUE_PREFIX" value = "TEST/QUEUE/PREFIX" />
<var name = "IN_QUEUE" value = "${QUEUE_PREFIX}/IN" />
<var name = "OUT_QUEUE" value = "${QUEUE_PREFIX}/OUT" />
<element>${IN_QUEUE}</element>
这应该导致
<var name = "QUEUE_PREFIX" value = "TEST/QUEUE/PREFIX" />
<var name = "IN_QUEUE" value = "TEST/QUEUE/PREFIX/IN" />
<var name = "OUT_QUEUE" value = "TEST/QUEUE/PREFIX/OUT" />
<element>TEST/QUEUE/PREFIX/IN</element>
使用此代码在 memory 中完成这些变量的替换。 请注意,我首先替换了变量声明部分中的变量,然后再继续在文档的主要部分中进行替换。
private static final String VAR_START = "\\$\\{"
private static final String VAR_END = "\\}"
private String fileContent = readFile(path);
private Map<String, String> variables = getVarsFromFile();
private void replaceInVariables() {
for(Entry<String, String> e : variables.entrySet()) {
fileContent = fileContent.replaceAll(VAR_START + e.getKey() + VAR_END, e.getValue);
}
}
我收到以下错误
named capturing group is missing trailing '}'
我的问题:
如何将“${”和“}”转义为文字字符串,以便它不将其用作正则表达式?
问题来自可能包含${
而没有}
的动态(用户定义)替换,因此正则表达式引擎会认为存在损坏的命名反向引用。
您可以在没有手动 escaping 的情况下保留分隔符,并依靠Pattern.quote
转义整个正则表达式模式,并依靠Matcher.quoteReplacement
转义替换模式:
private static final String VAR_START = "${";
private static final String VAR_END = "}";
// ...
fileContent = fileContent.replaceAll(Pattern.quote(VAR_START + e.getKey() + VAR_END), Matcher.quoteReplacement(e.getValue))
我可以建议一种不同的方法吗? 匹配所有出现的${...}
然后在回调中替换它们。 这看起来比多次替换字符串更直接、更有效。
Java 9 是这样的:
Map<String, String> variables = …;
Pattern pattern = Pattern.compile("\\$\\{([^}]+)\\}");
String replaced = pattern.matcher(your_input_string)
.replaceAll(mr -> {
String placeholderName = mr.group(1);
// fall back to placeholder when not defined:
return variables.getOrDefault(placeholderName, mr.group(0));
});
这是一个工作演示示例: https://ideone.com/3XxRk4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.