How to interpolate variables within a string using HashMap as variable source

Parchment :

Let's say we have a string: string text = "Hello my name is $$name; and my surname is $$surname;"

It references 2 variables, identified by double dollar sign: name and surname

We also have a hashmap:

HashMap<String, String> variables = new HashMap<String, String>();
variables.put("name", "John");
variables.put("surname", "Doe");

How do I replace/interpolate variables in a string with their matched Regex values as hashmap keys? (perhaps there's no need to use Regex and Java has this implementation)

In the end, I want variable string text to equal "Hello my name is John and my surname is Doe"

EDIT: What I meant is replacing the key/variable with the hashmap value without knowing the key. For example, we have a string and we must replace all $$variable; values inside in with the map[variable].

What would be the fastest way of replacing this string?

Dorian Gray :

You would have to use some regex, parse the input and lookup every key in the Map, like that:

import java.util.Map;
import java.util.regex.Pattern;

public class T2 {
    /** Pattern for the variables syntax */
    public static final Pattern PATTERN = Pattern.compile("\\$\\$([a-zA-Z]+);");

    public static void main(String[] args) {
        String s = "Hello my name is $$name; and my surname is $$surname;";
        Map<String, String> variables = Map.of("name", "John", "surname", "Doe");
        String ret = replaceVariables(s, variables);
        System.out.println(ret);
    }

    private static String replaceVariables(CharSequence s, Map<String, String> variables) {
        return PATTERN.matcher(s).replaceAll(mr -> variables.getOrDefault(mr.group(1), ""));
    }

}

Output:

Hello my name is John and my surname is Doe

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=366739&siteId=1