正则提取图片
public static List<String> extractImageUrls(String html) {
List<String> imageUrls = new ArrayList<>();
Pattern pattern = Pattern.compile("<img\\s+[^>]*?src\\s*=\\s*['\"]([^'\"]+?)['\"][^>]*?>", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(html);
while (matcher.find()) {
String imageUrl = matcher.group(1);
imageUrls.add(imageUrl);
}
return imageUrls;
}
标签剔除和替换
String html = "<p>你好,我们是一个团队。</p><p>我们正在学习jsoup。</p><div class=\"TAF\"><p>test</p></div>";
String replaceAll = html.replaceAll("<div class=\"TAF\">(.*?)</div>","<hr>$1</hr>");//替换div指定标签为hr
System.out.println(replaceAll);
replaceAll = html.replaceAll("<div[^>]*>(.*?)</div>","$1");//可以附加标签等<div>$1</div>
System.out.println(replaceAll);
replaceAll = html.replaceAll("<div[^>]*>(.*?)</div>","");//去除div指定标签和所有包裹的内容
System.out.println(replaceAll);
replaceAll = html.replaceAll("<div[^>]*>", "").replaceAll("</div>", "");//只去除div指定标签
System.out.println(replaceAll);
<p>你好,我们是一个团队。</p><p>我们正在学习jsoup。</p><hr><p>test</p></hr>
<p>你好,我们是一个团队。</p><p>我们正在学习jsoup。</p><p>test</p>
<p>你好,我们是一个团队。</p><p>我们正在学习jsoup。</p>
<p>你好,我们是一个团队。</p><p>我们正在学习jsoup。</p><p>test</p>
String html = "<div><span style='color:red;font-size:15px'><cts style='color:red;'>测试</cts>555</span></div>";
html= html.replaceAll("<cts[^>]*>(.*?)</cts>","$1");
System.out.println(html);
<div><span style='color:red;font-size:15px'>测试555</span></div>
replaceAll("[\\r\\n]+", "")去掉换行
replaceAll("[\\r\\n]+| +","")去掉换行和空格
replaceAll("\\s", "")去掉换行空格
String html = "<tps>测试\n </tps>";
System.out.println(StringEscapeUtils.escapeHtml(html));
System.out.println(StringEscapeUtils.unescapeHtml(html));