Skip to content

C#正则匹配图片

web240 edited this page Aug 29, 2016 · 3 revisions
一般来说一个 HTML 文档有很多标签,比如“<html>”、“<body>”、“<table>”等,想把文档中的 img 标签提取出来并不是一件容易的事。由于 img 标签样式变化多端,使提取的时候用程序寻找并不容易。于是想要寻找它们就必须写一个非常健全的正则表达式,不然有可能会找得不全,或者找出来的不是正确的 img 标签。
我们可以从 HTML 标签的格式去想应该怎么建这个正则表达式。首先要想一下 img 标签有几种写法,忽略大小写不看的话,下面列出 img 标签可能出现的几种情况。
<img> <img/> <img src=/> 
这一些标签不用考虑,因为没有图片资源地址。 
<img src = /images/pic.jpg/ > <img src =" /images/pic.jpg" > <img src= '/images/pic.jpg ' / >
这一些标签都有图片资源地址,另外还有一个特点就是有引号对,可能为单引号,也可能为双引号。因为不需要同时匹配引号对,所以正则表达式可以这么写:@"<img\s*src\s*=\s*[""']?\s*(?[^\s""'<>]*)\s*/?\s*>"
<img width="320" height="240" src=/images/pic.jpg onclick="window.open('/images/pic.jpg')">
因为 img 和 src 之间可能会有其他的参数,所以“<img”要有个单词结束,比如说不能是“<imgabc”,同样 src 前面也是一样,使用单词结束符“\b”有一个好处就是省去了表示空格的“\s*”。另外由于 img 标签中不可以出现“<”、“>”这样的符号,所以要改写前面的正则表达式:@"<img\b[^<>]*?\bsrc\s*=\s*[""']?\s*(?<imgUrl>[^\s""'<>]*)[^<>]*?/?\s*>"
<img width="320" height="240" src = " 
/images/pic.jpg" /> 
像这种可能会用回车符折行的问题有时候会出现,所以在有空格分开的地方要包含回车换行和 TAB 字符,另外在图片地址中不能出现空格、TAB、回车和换行字符。
所以上面的正则表达式可以改成:@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>"
    /// <summary> 
    /// 取得HTML中所有图片的 URL。 
    /// </summary> 
    /// <param name="sHtmlText">HTML代码</param> 
    /// <returns>图片的URL列表</returns> 
    public   string[] GetHtmlImageUrlList(string sHtmlText)
    {
        // 定义正则表达式用来匹配 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);
        int i = 0;
        string[] sUrlList = new string[matches.Count];

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


    public static string[] GetHtmlImageUrlList(string sHtmlText)
    {
        // 定义正则表达式用来匹配 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);
        int i = 0;
        string[] sUrlList = new string[matches.Count];
        // 取得匹配项列表
        foreach (Match match in matches)
            sUrlList[i++] = match.Groups["imgUrl"].Value;
        return sUrlList;
    }
    /** 
  • 从HTML源码中提取图片路径,最后以一个 String 类型的 List 返回,如果不包含任何图片,则返回一个 size=0 的List

  • 需要注意的是,此方法只会提取以下格式的图片:.jpg|.bmp|.eps|.gif|.mif|.miff|.png|.tif|.tiff|.svg|.wmf|.jpe|.jpeg|.dib|.ico|.tga|.cut|.pic

  • @param htmlCode HTML源码

  • @return 标签 src 属性指向的图片地址的List集合

  • @author Carl He / public static string getImageSrc(String htmlCode) { string html = @"<img width=""226"" height=""164"" alt=""caiyu"" width=""226"" height=""164"" alt=""caiyu"" src=""http://localhost:4677/UserDir/Images/3c7e9eec047148e9196b673998b898a5.jpg"" />应用开发测试<img alt="""" src=""http://localhost:4677/UserDir/Images/cebd0017aa6b743e4b90a70e.jpg"" />应用开发测试<a href=""http://localhost:4677/UserDir/Documents/f在区域自动气象站WEB平台中的应用(英文).pdf"">/UserDir/Documents/f在区域自动气象站WEB平台中的应用(英文).pdf"; var regimg = new Regex(@"(?<=src="").?(?="")", RegexOptions.IgnoreCase); var reghref = new Regex(@"(?<=href="").*?(?="")", RegexOptions.IgnoreCase); List src = new List(); List href = new List(); foreach (Match r in regimg.Matches(html)) { src.Add(r.Value); } foreach (Match r in reghref.Matches(html)) { href.Add(r.Value); }

         Regex reg = new Regex(@"(?is)(<img[^>]*?src=|\bbackground(?:=|:url\())(?!['""]?http://)((['""])(?<img>[^'"">)]+)\3|(?<img>[^'""\s)>]+))", RegexOptions.IgnoreCase);
         //Regex reg = 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);
         string result = reg.Replace(htmlCode, "$1$3http://****/${img}$3");
         return result;
     }
    
Clone this wiki locally