利用正则表达式获取网页中多处重复出现的标签数据
public static void main(String[] args) {
String regex = "<p style=\"TEXT-INDENT: 2em\">(.*?)</p>";
String html = "<p style=\"TEXT-INDENT: 2em\">ttt</p>yyyyyfafdasf<p style=\"TEXT-INDENT: 2em\">bbb</p>";
Pattern pattern = Pattern.compile(regex);
Matcher match = pattern.matcher(html);
StringBuffer buffer = new StringBuffer();
while(match.find()){
buffer.append(match.group(1));
buffer.append("\n");
}
System.out.println(buffer.toString());
}
说明:想要抓取网页中想要的文本,而每段文本都是存放在<p style=\"TEXT-INDENT: 2em\">开头和</p>结尾的标签中,所以我们想要的获取的是ttt和bbb,(.*?)表示一个分组,并且使用的是非贪婪的模式,即获取最小的匹配内容,match.find()返回的是是否找到匹配的内容,match.group(1)表示取出其中的文本内容