El siguiente código contiene una expresión regular diseñada para extraer un literal de cadena C#, pero el rendimiento de la expresión regular para cadenas de entrada de más de unos pocos caracteres es lamentable.Regex lento rendimiento
class Program
{
private static void StringMatch(string s)
{
// regex: quote, zero-or-more-(zero-or-more-non-backslash-quote, optional-backslash-anychar), quote
Match m = Regex.Match(s, "\"(([^\\\\\"]*)(\\\\.)?)*\"");
if (m.Success)
Trace.WriteLine(m.Value);
else
Trace.WriteLine("no match");
}
public static void Main()
{
// this first string is unterminated (so the match fails), but it returns instantly
StringMatch("\"OK");
// this string is terminated (the match succeeds)
StringMatch("\"This is a longer terminated string - it matches and returns instantly\"");
// this string is unterminated (so the match will fail), but it never returns
StringMatch("\"This is another unterminated string and takes FOREVER to match");
}
}
puedo refactorizar la expresión regular en una forma diferente, pero cualquier persona puede ofrecer una explicación de por qué el rendimiento es tan malo?
http://msdn.microsoft.com/en-us/magazine/ff646973.aspx – SLaks
Creo que es incorrecto. '[^ \"] 'no se detendrá en' \ "'. Se detendrá en '\' o en '" '. Así que se detendrá en el' \ 'de' \ n'. ¿Es correcto? – xanatos
Tal vez podrías modificar tu expresión regular si no estás usando las referencias "'. \ "(?: (?: [^ \\\"] *) (?: \\.)?) * \ "" '. Por supuesto, si ESTÁS utilizando las referencias, ignora esto. – Matthew