开发者

Regular expression in java to replace my placeholders with hashmap data

I have a template with placeholders

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

Message [[other.msg]]

And I a have collection of data in Map

Map 开发者_如何学Cdata = new HashMap();  
data.put("user.firstname","John");
data.put("user.lastname","Kannan");    
data.put("other.msg","Message goes here...");

I would like to create a Java regular expression to replace map data value with associated placeholder (within [[]]) on my template.


You can't do that using regex alone in Java, you need to wrap it in some logic.

Here's a method that does this for you:

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();

}


Why do you need a regex for this? Why not simply do :

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


I would recommend to use the appendReplacement method for this:

Map<String, String> data = new HashMap<String, String>();
...
Pattern p = Pattern.compile("\\[\\[([a-zA-Z.]+)\\]\\]");
Matcher m = p.matcher("Dear [[user.firstname]] [[user.lastname]]");
StringBuffer sb = new StringBuffer();
while (m.find()) {
    String reg1 = m.group(1);
    String value = data.get(reg1);
    m.appendReplacement(sb, Matcher.quoteReplacement(value == null ? "" : value));
}
m.appendTail(sb);


so, what's the problem?

String text = "Dear [[user.firstname]] [[user.lastname]]";
for (String key : data.keySet()) {
    String pattern = key.replace("[", "\\[").replace("]", "\\");
    text = text.replaceAll(pattern, data.get(key));
}

Be careful with . Probably you have to duplicate them, i.e. write \\ instead of \. Just debug your code a couple of minutes and the solution is ready.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜