C#使用正则表达式匹配富文本内的图片

2021/12/27 9:37:11

本文主要是介绍C#使用正则表达式匹配富文本内的图片,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

        /// <summary>
        /// 取得HTML中第一张图片的 URL。
        /// </summary>
        /// <param name="sHtmlText">HTML代码</param>
        /// <returns>图片的URL列表</returns>
        public string GetHtmlImageFirstUrl(string sHtmlText)
        {
            string firstImgUrl = string.Empty;
            // 定义正则表达式用来匹配 img 标签
            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);

            // 搜索匹配的字符串
            MatchCollection matches = regImg.Matches(sHtmlText);
            if (matches?.Count > 0)
            {
                string[] sUrlList = new string[matches.Count];

                // 取得匹配项列表
                foreach (Match match in matches)
                {
                    firstImgUrl = match.Groups["imgUrl"].Value;
                    break;
                }
            }
            return firstImgUrl;
        }

 



这篇关于C#使用正则表达式匹配富文本内的图片的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程