modo migliore di sostituire tutti i tag in una stringa con java
-
03-07-2019 - |
Domanda
Ho un metodo di servizio che accetta una stringa e quindi sostituisce i tag nella stringa con elementi da una libreria di tag. Come segue:
for( MetaDataDTO tag : tagValues )
{
message = message.replace( tag.getKey(), tag.getText1() );
}
Ovviamente; questo rende un sacco di nuove stringhe ed è MALE. Ma il metodo di sostituzione StringBuilder è scomodo da utilizzare per più stringhe all'interno di una stringa. Come posso rendere il mio metodo più efficiente?
È da utilizzare con blocchi di testo come:
Caro # firstName #, la tua domanda per # applicationType # è stata # approvataRejected # sorry #
Dove # firstName #, ecc. sono le chiavi in ??un database di metadati. È anche possibile che i tag non siano circondati da caratteri hash.
Soluzione 2
Grazie per l'aiuto ragazzi. Certamente imparato di più su Java. Ecco la mia soluzione È in questo modo per supportare tag e tag diversi nei tag:
private static String replaceAllTags(String message, Map< String, String > tags)
{
StringBuilder sb = new StringBuilder( message );
boolean tagFound = false;
/**
* prevent endless circular text replacement loops
*/
long recurrancyChecker = 5000;
do
{
tagFound = false;
Iterator it = tags.entrySet().iterator();
while( it.hasNext() )
{
Map.Entry pairs = (Map.Entry) it.next();
int start = sb.indexOf( pairs.getKey().toString() );
while( start > -1 && --recurrancyChecker > 0 )
{
int length = pairs.getKey().toString().length();
sb.replace( start, start + length, pairs.getValue().toString() );
start = sb.indexOf( pairs.getKey().toString() );
tagFound = true;
}
}
}
while( tagFound && --recurrancyChecker > 0 );
return sb.toString();
}
Altri suggerimenti
In pratica si desidera copiare l'esecuzione di Matcher.replaceAll () in questo modo:
public static String replaceTags(String message, Map<String, String> tags) {
Pattern p = Pattern.compile("#(\\w+)#");
Matcher m = p.matcher(message);
boolean result = m.find();
if (result) {
StringBuffer sb = new StringBuffer();
do {
m.appendReplacement(sb, tags.containsKey(m.group(1) ? tags.get(m.group(1)) : "");
result = m.find();
} while (result);
m.appendTail(sb);
message = sb.toString();
}
return message;
}
Nota: ho fatto un'ipotesi sul tag valido (vale a dire \ w nella regex). Dovrai soddisfare ciò per ciò che è veramente valido (ad es. & Quot; # ([\ w _] +) # ").
Ho anche supposto che i tag sopra assomiglino a:
Map<String, String> tags = new HashMap<String, String>();
tags.add("firstName", "Skippy");
e non:
tags.add("#firstName#", "Skippy");
Se il secondo è corretto, dovrai adeguarti di conseguenza.
Questo metodo effettua esattamente un passaggio attraverso la stringa del messaggio in modo che non diventi molto più efficiente di questo.