日期:2014-05-18  浏览次数:20338 次

高分求正则啦!
C# code
class Program
    {
        static void Main(string[] args)
        {
            string a = "xxxx <a>abcdxxxxyyyxxx</a> <a>xxxxyyy</a> xxxyyyxx <img alt=xxx/> yyy";

            Console.WriteLine(RegReplace(a, "yyy", "DDD"));
            Console.Read();
        }


        public static string RegReplace(string content, string oldstr, string newstr)
        {

            //这个正则有问题,第一次出现在a标签中的yyy仍被替换为DDD,与预期不符。求帮忙修改!
            return Regex.Replace(content, @"(?<!<a[^>]+>[^<]*)" + oldstr+ "(?![^(</a>)]*?</a>)", newstr, RegexOptions.IgnoreCase);

        }  
    }


要求替换结果为所有不在a标签和img标签中的yyy变为DDD,即最终显示结果为:
xxxx <a>abcdxxxxyyyxxx</a> <a>xxxxyyy</a> xxxDDDxx <img alt=xxx/> DDD

全部的分了 谢谢大家

------解决方案--------------------
C# code

            string a = "xxxx <a>abcdxxxxyyyxxx</a> <a>xxxxyyy</a> xxxyyyxx <img alt=xxx/> yyy";
            Dictionary<string, string> dic = new Dictionary<string, string>();
            int index=0;
            foreach (Match match in Regex.Matches(a, "(<a>[^<]+</a>)|(<img[^>]+/>)"))
            {
                dic.Add("rep_" + index.ToString(), match.Value);
                a = a.Replace(match.Value, "rep_" + index.ToString());
                index++;
            }
            a = a.Replace("yyy", "DDD");
            foreach (string s in dic.Keys)
                a = a.Replace(s, dic[s]);
            Console.WriteLine(a);