C# String/StringBuilder 大量替换出现 MemoryException

C# String/StringBuilder MemoryException on Large set of Replaces

我正在尝试找出一种更好的方法来操作大字符串并同时使用我无法做到的字符串和字符串生成器。 我下面的是一个接受字符串的函数,我们用正则表达式搜索该字符串以找到任何 links。 link 的任何出现我想将它们包装在有效的 link 文本中。我的问题是,我有一个数据库条目(字符串),其中有 101 link 个值需要替换,并且我遇到了内存问题。

是否有更好的解决方法。我已经将它包含在 string.replace 和 stringbuilder.replace 中,但都不起作用

    var resultString = new StringBuilder(testb);
    Regex regx = new Regex(@"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[.\!\/\w]*))?)", RegexOptions.IgnoreCase);
    MatchCollection mactches = regx.Matches(txt);

    foreach (Match match in mactches)
    {
        if(match.Value.StartsWith("http://") || match.Value.StartsWith("https://"))
            fixedurl = match.Value;
        else
            fixedurl = "http://" + match.Value;

         resultString.Replace(match.Value, "<a target='_blank' class='ts-link ui-state-default' href='" + fixedurl + "'>" + match.Value + "</a>");
        //testb = testb.Replace(match.Value, "<a target='_blank' class='ts-link ui-state-default' href='" + fixedurl + "'>" + match.Value + "</a>");
    }

您可以尝试以下方法。它可能在您的特定情况下表现更好。

Regex regx = new Regex(@"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[.\!\/\w]*))?)", RegexOptions.IgnoreCase);

string resultString = regx.Replace(txt, (match) => 
{
    string fixedurl = (match.Value.StartsWith("http://") || match.Value.StartsWith("https://"))
        ? match.Value
        : "http://" + match.Value;

     return "<a target='_blank' class='ts-link ui-state-default' href='" + fixedurl + "'>" + match.Value + "</a>";
});

已编辑:

顺便说一句,您的代码的问题似乎是 resultString.Replace 调用,因为它替换了所有出现的字符串,这可能导致代码进入无限循环,反复替换相同的字符串重新开始,直到遇到 OutOfMemoryException。