You can do this:
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
class Main {
public static void main(String[] args) {
String templateTexto = "{tag} {player} {abacaxi} {banana} > {msg}";
Map<String, String> substituicoes = new HashMap<>();
substituicoes.put("tag", "MODERADOR");
substituicoes.put("player", "João");
substituicoes.put("msg", "uma mensagem.");
Template template = new Template(templateTexto);
String substituido = template.substituir(substituicoes);
System.out.println(substituido);
}
}
class Template {
private final String template;
private final Set<String> tags;
public Template(String template) {
this.template = template;
this.tags = new TreeSet<>();
StringBuilder nomeVariavel = null;
boolean variavel = false;
for (char c : template.toCharArray()) {
if (!variavel && c == '{') {
variavel = true;
nomeVariavel = new StringBuilder();
} else if (variavel && c == '}') {
variavel = false;
tags.add(nomeVariavel.toString());
nomeVariavel = null;
} else if (variavel) {
nomeVariavel.append(c);
}
}
}
public String substituir(Map<String, String> substituicoes) {
String texto = template;
for (Map.Entry<String, String> entry : substituicoes.entrySet()) {
texto = texto.replace("{" + entry.getKey() + "}", entry.getValue());
}
for (String tag : tags) {
if (substituicoes.containsKey(tag)) continue;
texto = texto.replace("{" + tag + "} ", "");
texto = texto.replace("{" + tag + "}", "");
}
return texto;
}
}
Here's the output:
MODERADOR João > uma mensagem.
See here working on ideone.
In this code, the Template
class represents the text with the tags. It has a method for doing the substitution, according to Map
. Note that the implementation of class Template
is a small compiler (its constructor is based on a two state automaton).
In% w /%, the test is run. There, an instance of main
is built, Template
is constructed with the desired substitutions, substitutions are performed and the result is displayed.
The Map
method only starts with template text and exits by replacing the tags with substitutes specified in substituir
. After that, elements that are not found in Map
, which match the other tags, are deleted. Note the detail that he also worries about removing the space that may exist in the template after a tag that will be deleted.