最近需要从网页中通过正则获取img的链接,查了很多资料,最终把采用的贴出来:
int i = 0; // previewDom = Pattern.compile("<img/s+[^>]*/s*src/s*=/s*([‘]?)(?<url>/S+)‘?[^>]*>").matcher(previewDom).replaceFirst("<!--{img:"+i+"}-->"); Set<String> pics = new HashSet<>(); String img = ""; String regEx_img = "(?is)<img\\s*((?<key>[^=]+)=\"*(?<value>[^\"]+)\")+?\\s*/?>"; Pattern p_image; Matcher m_image; p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE); m_image = p_image.matcher(previewDom); // System.out.println(); String tempStr = previewDom; String dealStr = ""; while (m_image.find()) { // 得到<img />数据 img = m_image.group(); // 匹配<img>中的src数据 Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img); while (m.find()) { // 获取文章链接,并拼成合适的url dealStr = dealStr + PRE_DEAL_STR + i + MID_DEAL_STR + m.group(1) + POST_DEAL_STR; // tempStr = previewDom; // 将原文链接拼接 tempStr = tempStr.replace(img, "<!--{img:" + i + "}-->"); pics.add(m.group(1)); // tempStr = m_image.replaceFirst("<!--{img:" + i + "}-->"); i++; } }
原文:http://www.cnblogs.com/Mr-Persist/p/6274118.html