日期:2014-05-17  浏览次数:20483 次

关于关键字替换的功能,求教,附上代码
原文内容:我们都是百度的人啊怎么是goolge的人呢?
 被替换后: <a href=' Google.html'><a href=' 百度.html'><a href=' a.html'>我们</a></a></a>都是<a href=' Google.html'><a href=' <a href=' a.html'>百度</a>.html'>百度</a></a>的人啊怎么是goolge的人呢?
实际应该是:我们都是<a herf=百度.html>百度</a>的人啊怎么是<a herf=goolge.html>goolge</a>的人呢?

C# code
private bool DoAdd()
        {
            Regex reg = new Regex(@"(?:^|(?<!<(?:a|pre)\b(?>[^<>]*))>)(?>[^<>]*)(?:<|$)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            string result2 = reg.Replace(txtContent.Value, RegReplace);
            richTextBox2.Text = result2; 
.......
}

 List<string> tags = new List<string>(new string[] { "Google", "百度", "a"});
 List<string> tagssa = new List<string>(new string[] { "Google.html", "百度.html", "a.html" });
int index = -1;
string temp = string.Empty;
List<string> list = new List<string>();
List<string> list2 = new List<string>();

private string RegReplace(Match m)
{
    temp = m.Value;
    foreach (string tag in tags)
    {
        foreach(string tag2 in tagssa)
        {
        index = temp.IndexOf(tag);
        if (index > -1)
        {
            list.Add(tag);
            list2.Add(tag2);
            temp = temp.Substring(0, index) + "<a href=' " + tag2 + "'>" + tag + "</a>" + temp.Substring(index + tag.Length);
        }
         }
    }
    foreach (string s in list)
    {
        tags.Remove(s);
    }
    foreach (string s2  in list2)
    {
        tags.Remove(s2);
    }
    list.Clear();
    list2.Clear();
    return temp;
}



------解决方案--------------------
C# code
 string temp = @"我们都是百度的人啊怎么是google的人呢?";
                Dictionary<string, string> dic = new Dictionary<string, string>() { 
                    {"Google","Google.html"},
                    {"百度","百度.html"},
                    {"a","a.html"}
                };
                
                foreach (var item in dic)
                {
                    string pattern_dic = @"(?i)(?<![</])"+item.Key;
                    temp = Regex.Replace(temp, pattern_dic, a => {
                        return @"<a href='" + item.Value + "'>" + a.Value + "</a>";
                    });
                }
                //我们都是<a href='百度.html'>百度</a>的人啊怎么是<a href='Google.html'>google</a>的人呢?