gpt4 book ai didi

java正则表达式解析日志文件

转载 作者:行者123 更新时间:2023-12-02 05:56:19 24 4
gpt4 key购买 nike

我正在尝试解析日志文件,并且想从输入的行中提取参数。这是该行的示例:

"Apr  8 07:13:10 kali gnome-screensaver-dialog: gkr-pam: unlocked login keyring"

该程序给了我:

Date&Time: Apr 11 00:06:30
Hostname: kali
Program Name: gnome-screensaver-dialog
Log: gkr-pam: unlocked login keyring

但对于这一行:

"Apr  8 07:13:45 kali gnome-screensaver-dialog: pam_unix(gnome-screensaver:auth): authentication failure; logname= uid=0 euid=0 tty=:0.0 ruser= rhost=  user=root"

我的 java 出现错误。我的代码中的错误是“正则表达式不匹配”,这表明我的reges是假的。基本上,我想提取日期和时间、主机名、程序名称和日志消息问题在于提取程序名称,它是第一个冒号之前的第一件事,例如上面的行应该给我:

   Date&Time: Apr  8 07:13:45
Hostname: kali
Program Name: gnome-screensaver-dialog
Log: pam_unix(gnome-screensaver:auth): authentication failure; logname= uid=0 euid=0 tty=:0.0 ruser= rhost= user=root

这是我的部分java代码:

private class FileTailerListenerAdapter extends TailerListenerAdapter {
@Override
public void handle(String line) {
String logEntryPattern = "([\\w]+\\s[\\d]+\\s[\\d:]+) ([\\w]+) ([\\[\\]\\(\\)a-zA-Z0-9\\-]+)[?:] (.+)";
Pattern p = Pattern.compile(logEntryPattern);
Matcher matcher = p.matcher(line);

if (!matcher.matches()) {
System.err.println("Regular Expression not matching:");
System.err.println(line);
return;
}
System.out.println("Total groups: " + matcher.groupCount());
System.out.println("Date&Time: " + matcher.group(1));
System.out.println("Hostname: " + matcher.group(2));
System.out.println("Program Name: " + matcher.group(3));
System.out.println("Log: " + matcher.group(4));
System.out.println();
System.out.println();
}
}

任何帮助将不胜感激!

最佳答案

主机名和程序名称似乎不能包含空格 - 知道您可以大大简化正则表达式:使用空格字符单独的主机名、程序名称和日志消息 - 一切都会正常:

final String logEntryPattern = "(\\w+\\s+\\d+\\s+\\d{2}:\\d{2}:\\d{2})\\s+(\\S+)\\s+(\\S+):\\s+(.+)";
final Pattern p = Pattern.compile(logEntryPattern);
final Matcher matcher = p.matcher(line);

if (!matcher.matches()) {
System.err.println("Regular Expression not matching:");
System.err.println(line);
return;
}
System.out.println("Total groups: " + matcher.groupCount());
System.out.println("Date&Time: " + matcher.group(1));
System.out.println("Hostname: " + matcher.group(2));
System.out.println("Program Name: " + matcher.group(3));
System.out.println("Log: " + matcher.group(4));

关于java正则表达式解析日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23056376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com