使用Java和Regex帮助从html标记中提取文本

val*_*lll 2 html java regex tags

我想使用Regex从html文件中提取一些文本.我正在学习正则表达式,但我仍然无法理解它.我有一个代码,提取所有包含在下面的文本<body>,</body>这里是:

public class Harn2 {

public static void main(String[] args) throws IOException{

String toMatch=readFile();
//Pattern pattern=Pattern.compile(".*?<body.*?>(.*?)</body>.*?"); this one works fine
Pattern pattern=Pattern.compile(".*?<table class=\"claroTable\".*?>(.*?)</table>.*?"); //I want this one to work
Matcher matcher=pattern.matcher(toMatch);

if(matcher.matches()) {
    System.out.println(matcher.group(1));
}

}

 private static String readFile() {

      try{
            // Open the file that is the first 
            // command line parameter
            FileInputStream fstream = new FileInputStream("user.html");
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine = null;
            //Read File Line By Line
            while (br.readLine() != null)   {
                // Print the content on the console
                //System.out.println (strLine);
                strLine+=br.readLine();
            }
            //Close the input stream
            in.close();
            return strLine;
            }catch (Exception e){//Catch exception if any

                System.err.println("Error: " + e.getMessage());
                return "";
            }
}
}
Run Code Online (Sandbox Code Playgroud)

好吧它工作得很好但是现在我想在标签之间提取文本: <table class="claroTable"></table>

所以我替换了我的正则表达式字符串".*?<table class=\"claroTable\".*?>(.*?)</table>.*?" 我也试过 ".*?<table class=\"claroTable\">(.*?)</table>.*?" 但它不起作用我不明白为什么.html文件中只有一个表,但javascript代码中出现"table":"... dataTables.js ..."这可能是错误的原因吗?

提前谢谢你的帮助,

编辑:extranct的html文本是这样的:

<body>
.....
<table class="claroTable">
<td><th>some data and manya many tags </td>
.....
</table>
Run Code Online (Sandbox Code Playgroud)

我想提取的是<table class="claroTable">和之间的任何东西</table>

Sea*_*oyd 6

以下是使用JSoup解析器执行此操作的方法:

File file = new File("path/to/your/file.html");
String charSet = "ISO-8859-1";
String innerHtml = Jsoup.parse(file,charSet).select("body").html();
Run Code Online (Sandbox Code Playgroud)

是的,你也可以用regex以某种方式做到这一点,但它永远不会那么容易.

更新:你的正则表达式模式的主要问题是你错过了DOTALL标志:

Pattern pattern=Pattern.compile(".*?<body.*?>(.*?)</body>.*?",Pattern.DOTALL);
Run Code Online (Sandbox Code Playgroud)

如果你只想要指定的表标记包含内容,你可以这样做:

String tableTag = 
    Pattern.compile(".*?<table.*?claroTable.*?>(.*?)</table>.*?",Pattern.DOTALL)
           .matcher(html)
           .replaceFirst("$1");
Run Code Online (Sandbox Code Playgroud)

(更新:现在只返回表标记的内容,而不是表标记本身)