java中的正则表达式用hashmap数据替换我的占位符

Ram*_*nan 3 java regex

我有一个带占位符的模板

Dear [[user.firstname]] [[user.lastname]] 

Message [[other.msg]]
Run Code Online (Sandbox Code Playgroud)

我在Map中收集了数据

Map data = new HashMap();  
data.put("user.firstname","John");
data.put("user.lastname","Kannan");    
data.put("other.msg","Message goes here...");
Run Code Online (Sandbox Code Playgroud)

我想创建一个Java正则表达式来替换[[]]我的模板上的关联占位符(内)的地图数据值.

Sea*_*oyd 11

你不能在Java中单独使用regex,你需要将它包装在一些逻辑中.

这是一个为您执行此操作的方法:

public static String replaceValues(final String template,
    final Map<String, String> values){

    final StringBuffer sb = new StringBuffer();
    final Pattern pattern =
        Pattern.compile("\\[\\[(.*?)\\]\\]", Pattern.DOTALL);
    final Matcher matcher = pattern.matcher(template);
    while(matcher.find()){
        final String key = matcher.group(1);
        final String replacement = values.get(key);
        if(replacement == null){
            throw new IllegalArgumentException(
               "Template contains unmapped key: "
                + key);
        }
        matcher.appendReplacement(sb, replacement);
    }
    matcher.appendTail(sb);
    return sb.toString();

}
Run Code Online (Sandbox Code Playgroud)


JB *_*zet 5

为什么你需要一个正则表达式?为什么不简单地做:

for (Map.Entry<String, String> replacement : data.entrySet()) {
    s = s.replace("[[" + replacement.getKey() + "]]", replacement.getValue());
}
Run Code Online (Sandbox Code Playgroud)