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?
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(final CharSequence s, final Map<? super 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