通过正则从内容中匹配图片,并找到src值

例子:

            string result = "";

            string str = "测试文字<img src=\"/upload/2016-05/2016052314264421.jpg\" alt=\"\" title=\"\" />测试文字<img title=\"\" src=\"/upload/2016-05/2016052314262994.png\" alt=\"\" />测试文字<img src=\"/upload/2016-05/2016052314262994.jpg\" alt=\"\" title=\"\" />测试文字";
            Regex reg = new Regex("(i?)<img.*? src=\"?(.*?\\.(jpg|gif|bmp|bnp|png))\".*? />");   //定义正则表达式
            MatchCollection mc = reg.Matches(str);  //在内容中匹配与正则表达式匹配的字符
            foreach (Match m in mc)     //循环匹配到的字符
            {
                int srcIndex = m.Value.IndexOf("src=\"");
                string strSrc = m.Value.Substring(srcIndex);
                int firstIndex = strSrc.IndexOf("\"");
                int lastIndex = strSrc.IndexOf("\"", firstIndex + 1);

                string src = strSrc.Substring(firstIndex + 1, lastIndex - firstIndex - 1);
                string srcPath = Server.MapPath(src);

                result += srcPath + "<br/>"; 
                
                //Response.Write(m.Value + "<br/>");
            }

            Response.Write(result);

    原文作者:猿序程
    原文地址: https://blog.csdn.net/wei_jie_zhang/article/details/53080073
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞