使用Java Regex在html中提取文本

时间:2016-05-10 05:40:17

标签: java html regex

我需要从html标签中提取文本。我写了一段代码,但文本没有被提取出来。以下是我的代码

import java.util.regex.Matcher;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.regex.Pattern;
class getFontTagText{
String result = null;
public static void main(String args[]){
    try{
           getFontTagText text = new getFontTagText();
           BufferedReader r = new BufferedReader(new FileReader("target.html"));
           Pattern p = Pattern.compile("<FONT FACE=\"Arial\" SIZE=\"1\" COLOR=\"\\W|_000000\" LETTERSPACING=\"0\" KERNING=\"0\">(//AZUZZU Full Service Provision)</FONT>",Pattern.MULTILINE);
           String line;
           System.out.println("Came here");
           while((line = r.readLine()) != null){
           Matcher mat = p.matcher(line);

           while(mat.find()){
                System.out.println("Came here");
                String st = mat.group(1);
                System.out.format("'%s'\n", st);
            }
        }
    }catch (Exception e){
        System.out.println(e);
    }
}

}

并且html文件在这里

     <P ALIGN="LEFT">
         <FONT FACE="Arial" SIZE="1" COLOR="#000000" LETTERSPACING="0" KERNING="0">ZUZZU Full Service Provision</FONT>
     </P>
     <P ALIGN="LEFT">
         <FONT FACE="Arial" SIZE="1" COLOR="#000000" LETTERSPACING="0" KERNING="0">&uuml; &ouml; &auml; &Auml; &Uuml; &Ouml; &szlig;</FONT>
     </P>

mat.group(1)正在打印&#39; null&#39;而不是文字。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我建议使用jsoup。 jsoup是一个Java库,用于使用CSS和类似jquery的方法提取和操作HTML数据。在你的情况下,它看起来像这样:

    public static void jsoup() throws IOException{
    File input = new File("C:\\users\\uzochi\\desktop\\html.html");
    Document doc = Jsoup.parse(input, "UTF-8");
    Elements es = doc.select("FONT");//select tag 
    for(Element e : es){
        System.out.println(e.text());
    }    
}

如果您更喜欢使用正则表达式,只需匹配&gt;之间的文本。和&lt; ,例如

public static void regex(){
Pattern pat = Pattern.compile("<FONT [^>]*>(.*?)</FONT>");//
String s = "<html>\n" +
            "<body>\n" +
            "\n" +
            "<P ALIGN=\"LEFT\">\n" +
            "         <FONT FACE=\"Arial\" SIZE=\"1\" COLOR=\"#000000\" LETTERSPACING=\"0\" KERNING=\"0\">ZUZZU Full Service Provision</FONT>\n" +
            "     </P>\n" +
            "     <P ALIGN=\"LEFT\">\n" +
            "         <FONT FACE=\"Arial\" SIZE=\"1\" COLOR=\"#000000\" LETTERSPACING=\"0\" KERNING=\"0\">&uuml; &ouml; &auml; &Auml; &Uuml; &Ouml; &szlig;</FONT>\n" +
            "     </P>\n" +
            "\n" +
            "</body>\n" +
            "</html>";
Matcher m = pat.matcher(s);
while (m.find()) {
    String found = m.group(1);
    System.out.println("Found : " + found);      
}    

}