Regular expression in java to replace my placeholders with hashmap data

I have a placeholder template

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

Message [[other.msg]]

And I have a dataset in Map

Map data = 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 the value of the map data with the associated placeholder (inside [[]]) on my template.

+3
source share
4 answers

You cannot do this using only regex in Java, you need to wrap it in some logic.

Here is the way 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();

}
+9
source

Why do you need regex? Why not just do:

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

appendReplacement:

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);
+1

, ?

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

. , , .. \\ \. , .

-1
source

Source: https://habr.com/ru/post/1790424/


All Articles