我有一个小API,可以通过更新属性持有者将字符串转换为另一个字符串(模式{{property_name}}
这是我的尝试:
public class TestApp {
public static void main(String[] args) {
Map<String, String> props = new HashMap<>();
props.put("title", "login");
String sourceTitle = "<title>{{ title }}</title>";
System.out.println(updatePropertyValue(sourceTitle, props));
// Print: <title>login</title>
// ERROR if
props.put("title", "${{__messages.loginTitle}}");
System.out.println(updatePropertyValue(sourceTitle, props));
// Expected: <title>${{__messages.loginTitle}}</title>
// Exception:
// Exception in thread "main"
// java.lang.IllegalArgumentException: named capturing group has 0 length name
// at java.util.regex.Matcher.appendReplacement(Matcher.java:838)
}
static String updatePropertyValue(String line, Map<String, String> properties) {
for (Entry<String, String> entry : properties.entrySet()) {
String holder = "\\{\\{\\s*" + entry.getKey() + "\\s*\\}\\}";
line = Pattern.compile(holder, Pattern.CASE_INSENSITIVE)
.matcher(line).replaceAll(entry.getValue());
}
return line;
}
}
如果属性值没有任何特殊字符(例如$),则可以正常工作。
请假定属性键仅包含字母。
有什么办法吗?谢谢!
最佳答案
使用Pattern.quoteReplacement
转义替换中的所有元字符。
关于java - Java用另一个子字符串(值)替换子字符串(模式),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41448637/