【问题标题】:java - filter log file by regexjava - 通过正则表达式过滤日志文件
【发布时间】:2020-04-24 21:40:43
【问题描述】:

我需要从日志中过滤数据,并且我需要过滤数据,这包含时间 13:00-14:59。 但是这个和许多其他的诱惑都失败了。什么都没有显示 Log file

我的方法:

public static void Proccesing(File file){
    String formula = ".*1(3 [0-5][0-9]|4 [0-5][0-9]).*";

    try{
        BufferedReader rd= new BufferedReader(new FileReader(file));
        String line = rd.readLine();
        Pattern pattern = Pattern.compile(formula);
        Matcher matcher = pattern.matcher(line);

        while(line != null){
            matcher.reset(line);
            if(matcher.find()){
                line = rd.readLine();
                System.out.println(line);

            }

        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

【问题讨论】:

  • 我不确定为什么 rd.readLine() 在你的 if 语句中,而不是像 while((line=rd.readLine()) != null) 或 do-while 循环中的第一行
  • 第一次出现一行不匹配时,您将陷入无限循环,因为您永远不会阅读下一行。
  • 您能否详细解释一下您的正则表达式应该做什么?我很确定第一个和最后一个 .* 都可以而且应该被删除。
  • @user 谢谢。它是固定的。

标签: java regex pattern-matching


【解决方案1】:

您可以使用 Java8 方法过滤日志:

public static void process(String logFile) throws IOException {
    Files.lines(Path.of(logFile))
        .filter(s -> s.matches(".*1(3 [0-5][0-9]|4 [0-5][0-9]).*"))
        .forEach(System.out::println);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-03
    • 2010-09-26
    • 1970-01-01
    • 2019-05-25
    相关资源
    最近更新 更多