hice un comentario anterior preguntando por qué el título fue cambiado a asumir expresiones regulares se iba a utilizar.
Personalmente trato de no usar Regex porque es lento. Regex es ideal para patrones complejos de cuerdas, pero si los reemplazos de cuerdas son simples y necesita un poco de rendimiento, intentaré encontrar un camino sin usar Regex.
Hicieron una prueba juntos. Ejecutando un millón de reemplazos con Regex y métodos de cadena.
Regex tomó 26,5 segundos para completar, métodos de cadena tomaron 8 segundos para completar.
//Using Regex.
Regex r = new Regex(@"\b[Tt]he\b");
System.Diagnostics.Stopwatch stp = System.Diagnostics.Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++)
{
string str = "The man is old. The is the Good. Them is the bad.";
str = r.Replace(str, "@@");
}
stp.Stop();
Console.WriteLine(stp.Elapsed);
//Using String Methods.
stp = System.Diagnostics.Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++)
{
string str = "The man is old. The is the Good. Them is the bad.";
//Remove the The if the stirng starts with The.
if (str.StartsWith("The "))
{
str = str.Remove(0, "The ".Length);
str = str.Insert(0, "@@ ");
}
//Remove references The and the. We can probably
//assume a sentence will not end in the.
str = str.Replace(" The ", " @@ ");
str = str.Replace(" the ", " @@ ");
}
stp.Stop();
Console.WriteLine(stp.Elapsed);
¿Por qué fue el título editado para incluir expresiones regulares? Hay más de una forma de reemplazar el texto. Normalmente trato de evitar Regex porque es lento, así que no creo que el título debería haber sido editado para incluir la respuesta "asumida". – Crispy
@Chris Persichetti: Eso es suficiente; Eliminé "regex" del título. (Lo había agregado basado en las etiquetas, pero aparentemente "regex" no era una de las etiquetas originales.) –