zhuwei2008 发表于 2013-2-7 16:23:53

正则表达式提取html中的内容

public class Test {

    public static void main(String args[]) {
      String html = "<title>ABCD</title>gsdggas<title></title>jkll<title>005</title>";
      // 简单示例,相当于String html=getHtml(String urlString);
      List resultList = getContext(html);
      for (Iterator iterator = resultList.iterator(); iterator.hasNext();) {
            String context = (String) iterator.next();
            System.out.println(context);
      }
    }
   
    /**
   * 提取"<title>XXXX</title>"中的文字XXXX
   * @param html 要解析的html文档内容
   * @return 解析结果,可以多次匹配,每次匹配的结果按文档中出现的先后顺序添加进结果List
   */
    public static List getContext(String html) {
      List resultList = new ArrayList();
      Pattern p = Pattern.compile("<title>([^</title>]*)");//匹配<title>开头,</title>结尾的文档
      Matcher m = p.matcher(html );//开始编译
      while (m.find()) {
            resultList.add(m.group(1));//获取被匹配的部分
      }
      return resultList;
    }
}
页: [1]
查看完整版本: 正则表达式提取html中的内容