1
I have a template qualquer nome:{{UDA_numero qualquer}}
that comes "loose" in a String
. In that String
, there can be "n" templates, words, numbers, etc.
The goal is to catch this "any number" from the template and process it in a series of operations to replace with a description corresponding to the number. Still, it would be necessary to ignore all the other elements of the String
and replace only the template, keeping all other characters unchanged.
Ex:
String: "teste:{{UDA_1}} teste2:{{UDA_2}} teste3:{{UDA_3}} "
String(processada): "teste:descriacao_1 teste2:descricao_2 teste3:descricao_3
The problem is that String
of origin can come in any way possible, for example:
Origem: "teste:{{UDA_1}}, teste2:{{UDA_2}}, teste3:{{UDA_3}}..."
Processado: "teste:descricao_1, teste2:descricao_2, teste3:descricao_3..."
Origem: "teste:{{UDA_1}} \n teste2:{{UDA_2}} \n teste3:{{UDA_3}} \n"
Processada: "teste:descricao_1 \n teste2:descricao_2 \n teste3:descricao_3 \n"
Origem: "teste:descricao_1teste2:descricao_2teste3:descricao_3"
Processada: "teste:{{UDA_1}}teste2:{{UDA_2}}teste3:{{UDA_3}}"
Origem:"teste:{{UDA_1}} abc teste2:{{UDA_2}} 123 teste3:{{UDA_3}} ^~{{}}"
Processada: "teste:descricao_1 abc teste2:descricao_2 123 teste3:descricao_3 ^~{{}}"
Origem: "teste:{UDA_1}, teste2:{{UDA~~~2}}, teste3:{{3_UDA}}"
Processada: "teste:{UDA_1}, teste2:{{UDA~~~2}}, teste3:{{3_UDA}}"
// (Template está errado - não substitui).
Making it necessary to search for the template pattern in order to replace correctly. The way I was trying today, was using regex with the following idea:
// Padrão para acessar somente os templates
Pattern p = Pattern.compile("(\\{\\{(.\\w+.\\w.)\\}})+",Pattern.DOTALL);
// String recebida
Matcher m = p.matcher(ImportDescriptionValue);
// Sempre que encontrar o valor correspondente
while (m.find()) {
// Pega somente a parte de dentro (ex: UDA_1)
String uda = m.group(2);
// Formatar String para pegar somente o id
String idUDA = uda.substring(uda.indexOf('_')+1);
// **
... operações com o ID
if(encontrou descrição correspondente)
// Altera o atual pela descrição
m.replaceFirst(description);
}
else {
//Replace por "vazio" quando não encontrar.
m.replaceFirst("");
}
}
// String processada.
System.out.printl(m);
The code is wrong, but the idea would be more or less this. I have a solution that can solve by substituting right through the split()
, but due to all these possible variations, it is very limited. So I was trying to use other approximations to the problem, like regex for example.
My question:
- Regex is a good way to deal with this problem?
- Is there any good/optimized way to solve this problem?
In java the string replaceAll method supports a regex. nor would it need all that there not.
– Lucas Miranda
Yes, but each template has a different description... if I used replaceAll() they would all have the same description, wouldn’t they? I would need separate replace() for each template to have its description.
– David