C# 查找和替换HTML 文本中的Img标签的值


  public static List<string> SearchImage(string htmlText)
        {
            List<string> imgList = new List<string>();
            Regex regImg = new Regex(@"]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>");
            MatchCollection matches = regImg.Matches(htmlText);
            for (int i = 0; i < matches.Count; i++)
            {
                imgList.Add(matches[i].Groups["imgUrl"].Value);
            }
            return imgList;
}
 public static string Replace(string html)
        {
            string relust = string.Empty;
            string pattern = @"]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>";
            relust = Regex.Replace(html, pattern, (c =>
            {
                string newValue = string.Empty;
                string oldImgUrl = c.Groups["imgUrl"].Value;
                if (!String.IsNullOrEmpty(oldImgUrl))
                {
                    if (oldImgUrl.Contains("http"))
                    {
                        newValue = c.Value.Replace(oldImgUrl, oldImgUrl); ;
                    }
                    else
                    {
                        string bb = GetPath(@"Resource") + oldImgUrl;//需要替换的图片地址
                        newValue = c.Value.Replace(oldImgUrl, bb);
                    }
                }
                return newValue;
            }));
            return relust;
        }

相关