java正则表达式提取html中的图片标签

需求:将网页分享给其他人,JShare的分享模板如下:



其中有标题(红色)、内容(黄色)、图片(绿色),但是接口中没有给图片的URL,而html格式的内容中有<img src="http://……">标签,需要去内容中自己提取第一张图片作为分享的图标,如下:

所以,这个时候我们的需求就一目了然了:用正则表达式从繁杂的内容中找到我们需要的图片。

解决:
1、正则表达式:(http://jszx-jxpt.cuit.edu.cn/JavaAPI/java/util/regex/Pattern.html)官方API,供查询了解
2、代码查找:
一、先找到<img src="">标签,用到的正则表达式("<img.*?>")
代码如下:
 

public static List<String> getMatchString(){
    List<String> pics = new ArrayList<>(); // 因文件可能有多张图片,故用集合来存储结果
    Pattern compile = null;
    if (isDistinguish){ // isDistinguish:是否区分大小写
        compile = Pattern.compile("<img.*?>"); // "<img.*?>" : 获取标签的正则
    }else{
        compile = Pattern.compile("<img.*?>", Pattern.CASE_INSENSITIVE);
    }
    Matcher matcher = compile.matcher(string); // string:后台返的内容,图片就是从中提取的
    while (matcher.find()){
        String img = matcher.group();
        pics.add(img);
    }
    return pics;
}

运行,得到结果如下:

可以看出,本文有三张图片

二、再拿到标签中的地址,直接可以使用,代码如下:
 

List<String> img_url = new ArrayList<>();
/**
* img : 上面打印的标签内容,将它直接提取为我们要的http……
*
* "\"http?(.*?)(\"|>|\\s+)" : 获取src中 "" 图片地址的正则
*/
Matcher m = Pattern.compile("\"http?(.*?)(\"|>|\\s+)").matcher(img); 
m.find();
String url = m.group()
img_url.add(url.substring(1, url.length()-1));

运行,得到的结果如下:

可以看出,直接光秃秃的图片地址裸露在脸前,可以直接用了

最后贴出完整代码
 

    /**
    * regex:获取<img src="">标签的正则("<img.*?>")
    * string:提取图片标签的内容
    * isDistinguish:是否区分大小写
    */
    public static List<String> getMatchString(String regex, String string, boolean isDistinguish){
        List<String> pics = new ArrayList<>();
        Pattern compile = null;
        if (isDistinguish){
            compile = Pattern.compile(regex);
        }else{
            compile = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        }
        Matcher matcher = compile.matcher(string);
        while (matcher.find()){
            String img = matcher.group();
//            pics.add(img); // 如果只需要标签,那到这一步就可以了,如果直接需要图片URL,copy代码到最后
            /**
            * reg_html_img_src_http: 获取src中 "" 图片地址的正则("\"http?(.*?)(\"|>|\\s+)")
            * 
            * 获取标签中src的正则表达式("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)")
            */
            Matcher m = Pattern.compile(reg_html_img_src_http).matcher(img);
            m.find();
            String group = m.group();
            pics.add(group.substring(1, group.length() - 1));
        }
        return pics;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章