以下のコードには、C#文字列リテラルを抽出するために設計された正規表現が含まれていますが、数文字以上の入力文字列の正規表現マッチングの実行は大変です。遅い正規表現のパフォーマンス
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");
}
}
正規表現を別の形式にリファクタリングすることはできますが、その理由は誰でも説明できますか?
http://msdn.microsoft.com/en-us/magazine/ff646973.aspx – SLaks
私は間違っていると思います。 '[^ \"] 'は' \ "で停止しません。 – xanatos
逆参照を使用していない場合は、あなたの正規表現を修正することができます。 '' \ 'または '' \'で止まるでしょう。 \ "(?:(?:[^ \\\"] *)(?:\\。)?)* \ "" 'もちろん、逆参照を使用している場合は、これを無視してください。 – Matthew