C# 利用正则表达式获取富文本框中所有图片路劲

直接上代码

public static string[] GetHtmlImageUrlList(string htmlText)
        {
            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]*>", RegexOptions.IgnoreCase);

            //新建一个matches的MatchCollection对象 保存 匹配对象个数(img标签)
            MatchCollection matches = regImg.Matches(htmlText);
            int i = 0;
            string[] sUrlList = matches.Count >= 3 ? new string[3] : new string[matches.Count];
            //遍历所有的img标签对象
            foreach (Match match in matches)
            {
                //获取所有Img的路径src,并保存到数组中
                if (i <= 2)
                {
                    sUrlList[i++] = match.Groups["imgUrl"].Value.AddImgPathPrefix();
                }
            }
            return sUrlList;
        }
1 string content = "<p>测试<img src=\"/Uploads/Images/UEditor/2020052417350496181.jpg\" title=\"pic.jpg\" alt=\"pic.jpg\"/></p><p><br/></p><p><img src=\"/Uploads/Images/UEditor/2020052417361071834.jpg\" title=\"pic2.jpg\" alt=\"pic2.jpg\"/></p><p><br/></p>";
2             string[] array = Models.UtiServer.GetHtmlImageUrlList(content);

相关推荐