Ich muss in einem Text alles finden, was mit [ beginnt und mit ] endet, und es durch den Wert ersetzen, den eine Funktion zurückgibt. Hier ist also ein Beispiel für das, was ich tue:
public string ProcessTemplate(string input)
{
return Regex.Replace(input, @"\[(.*?)\]", new MatchEvaluator(delegate(Match match)
{
return ProcessBlock(match.Result("$1"));
}));
}
public string ProcessBlock(string value)
{
return Block.FromString(value).Process();
}
Mein Problem ist jetzt, dass ich Blöcke bearbeiten muss. Also dachte ich, ich suche Blöcke, bearbeite sie, und puis sie im Text zu ersetzen.
Also erstellte ich eine Liste von Blöcken und trennte die ProcessTemplate
Methode auf zwei Methoden: FindBlocks
y ReplaceBlocks
:
public void FindBlocks(string input)
{
Input = input;
foreach (Match match in Regex.Matches(input, @"\[(.*?)\]"))
Blocks.Add(Block.FromString(match.Result("$1")));
}
public string ReplaceBlocks()
{
string input = Input;
foreach (Block block in Blocks)
input = input.Replace("[" + block.OrginalText + "]", block.Process);
return input;
}
public IList<Block> Blocks
{
get;
set;
}
public string Input
{
get;
set;
}
Es funktioniert zwar, aber das Problem ist, dass es ziemlich langsam ist. Ich habe gemessen mit System.Diagnostics.Stopwatch
jedes Teil, und ich fand heraus, dass die String.Replace
im ReplaceBlocks
Methode ist ziemlich langsam.
Wie kann ich sie verbessern?
Gracias.