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();
}
source
share