日期:2014-05-18 浏览次数:20338 次
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); } }
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);