使用正则表达式进行流模式匹配

时间:2016-01-14 16:34:05

标签: java regex warc

我想解析一个用Warc 0.9版格式化的大文本文件。此类文本的示例为here。如果您查看它,您会发现整个文档包含以下条目列表。

[Warc Headers]

[HTTP Headers]

[HTML Content]

我需要从每个条目中提取URL和HTML内容(请注意,示例文件包含多个页面条目,每个条目的格式与上面的内容类似。)

我在Java中使用了以下正则表达式:

Pattern.compile("warc/0\\.9\\s\\d+\\sresponse\\s(\\S+)\\s.*\n\n.*\n\n(.*)\n\n", Pattern.DOTALL)

第1组和第2组分别代表URL和HTML内容。这段代码存在两个问题:

  1. 找到一场比赛很慢。
  2. 仅与第一页匹配。
  3. Java代码:

    if(mStreamScanner.findWithinHorizon(PAGE_ENTRY, 0) == null){
        return null;
    } else {
        MatchResult result = mStreamScanner.match();
        return new WarcPageEntry(result.group(1), result.group(2));
    }
    

    问题:

    • 为什么我的代码只解析第一页条目?
    • 是否有更快的方式以流方式解析大文本?

1 个答案:

答案 0 :(得分:0)

我不会用正则表达式处理这些巨大的HTML字符串。那么依赖于文档的结构呢?

E.g。像这样:

HashMap<String, String> output = new HashMap<>();
Pattern pattern = Pattern.compile("^warc\\/0\\.9\\s\\d+\\sresponse\\s(\\S+)\\s.*");

try (InputStreamReader is = new InputStreamReader(new FileInputStream("excerpt.txt"), "UTF-8")) {               
    try (BufferedReader br = new BufferedReader(is)) {      
        String line;        
        while ((line = br.readLine()) != null) {
            Matcher matcher = pattern.matcher(line);

            if (matcher.matches()) {
                entityLoop: while (true) {
                    String url = matcher.group(1);

                    // skip header
                    int countEmptyLines = 0;
                    while ((line = br.readLine()) != null) {
                        if ("".equals(line)) {
                            countEmptyLines++;
                            if (countEmptyLines == 2) break;
                        }
                    }

                    // extract HTML
                    StringBuilder sb = new StringBuilder();
                    while ((line = br.readLine()) != null) {
                        matcher = pattern.matcher(line);
                        if (matcher.matches()) { 
                            // got all HTML; store our findings
                            output.put(url, sb.toString());
                            continue entityLoop; 
                        }
                        sb.append(line);
                    }
                    break; // no more url/html-entities available
                }
            }
        }
    }       
} catch (IOException e) {
    // do something smart
}

// now all your extracted data is stored in "output"

上述代码仍有改进的余地。但它应该让你知道如何开始。