You can do it like 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 way out:
MODERADOR João > uma mensagem.
See here working on ideone.
In this code, the class Template
represents the text with the tags. It has a method to do the substitution, according to a Map
. Note that the class implementation Template
is a small compiler (its constructor is based on a two-state automaton).
In the main
, his test is carried out. There, an instance of the Template
, is built the Map
with the desired substitutions, the substitutions are performed and the result is displayed.
The method substituir
only starts with the template text and exits by replacing the tags with the substitutes specified in Map
. After that, the elements that are not found in the Map
, that match the other tags, are deleted. Note the detail that he also cares about taking away any space in the template after a tag that will be deleted.
+1 Legal this use of format :)
– user28595
I think the idea was to eliminate
[pvp]
of output.– Victor Stafusa