有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用Java正则表达式提取html中的文本

我需要从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>

垫子。组(1)被打印为“null”,而不是文本。非常感谢您的帮助


共 (1) 个答案

  1. # 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());
        }    
    }
    

    如果您更喜欢使用正则表达式,只需将文本与>;以及<,比如

    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);      
    }    
    

    }