最近須要從網頁中經過正則獲取img的連接,查了不少資料,最終把採用的貼出來:url
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++; } }