Java 正则表达式匹配img标题的src值

来源:互联网 发布:u盘数据丢失恢复 编辑:程序博客网 时间:2024/05/22 02:27
  1. public static List<String> getImgSrcList(String content){
  2. List<String> list = new ArrayList<String>();
  3. //目前img标签标示有3种表达式
  4. //<img alt="" src="1.jpg"/> <img alt="" src="1.jpg"></img> <img alt="" src="1.jpg">
  5. //开始匹配content中的<img />标签
  6. Pattern p_img = Pattern.compile("<(img|IMG)(.*?)(/>|></img>|>)");
  7. Matcher m_img = p_img.matcher(content);
  8. boolean result_img = m_img.find();
  9. if (result_img) {
  10. while (result_img) {
  11. //获取到匹配的<img />标签中的内容
  12. String str_img = m_img.group(2);
  13. //开始匹配<img />标签中的src
  14. Pattern p_src = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");
  15. Matcher m_src = p_src.matcher(str_img);
  16. if (m_src.find()) {
  17. String str_src = m_src.group(3);
  18. list.add(str_src);
  19. }
  20. //匹配content中是否存在下一个<img />标签,有则继续以上步骤匹配<img />标签中的src
  21. result_img = m_img.find();
  22. }
  23. }
  24. return list;
  25. }
2 0