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


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