Regex reg = new Regex(pattern, RegexOptions.IgnoreCase);
        MatchCollection mc = reg.Matches(html);
        foreach (Match match in mc)
        {***}有没有办法 每次循环 只替换当前 match 为新的 string 而不会 把 所有 与match.value 相同的 匹配项 全部替换我想要 单个替换 不想要 Replace 批量替换

解决方案 »

  1.   


     MatchCollection mc = Regex.Matches(tempStr, pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                string temp = mc[mc.Count - 1].Value;//得到最后一个(如果是最新的话,直接替换该值,这种需求不需要循环)
      

  2.   

    循环式肯定要的 我要替换 所有满足正则表达式 的 字符串string pattern = @"(href|src)=(""|')?(\S*?)(\2| )";
    懂了吧
      

  3.   

    问题解决了
    使用 while(true)做循环
    使用 Regex.Match(oldstr,startindex) 每次只匹配一个替换自己写了个 单替换方法 防止Replace 的批量替换
    /// <summary>
        /// 单一替换
        /// </summary>
        /// <param name="oldstr">原始字符串</param>
        /// <param name="index">替换开始位置</param>
        /// <param name="length">替换长度</param>
        /// <param name="newstr">要替换的新字符串</param>
        /// <returns></returns>
        public static string ReplaceSingle(string oldstr, int index, int length, string newstr)
        {
            oldstr = oldstr.Remove(index, length);
            oldstr = oldstr.Insert(index, newstr);
            return oldstr;
        }
    每次循环后 修改原始字符串,修改匹配起始位置