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

  public static List<string> SearchImage(string htmlText)
        {
            List<string> imgList = new List<string>();
            Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\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 = @"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\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;
        }

 

posted @ 2021-12-26 21:47  探索的动机  阅读(408)  评论(0编辑  收藏  举报