java正则表达式提取html中的图片标签<img src="">

需求:将网页分享给其他人,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;
    }

 

  • 8
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值