gpt4 book ai didi

java - 如何在 Java 中使用 java.regex.Matcher 解析日志文件

转载 作者:行者123 更新时间:2023-11-29 03:22:08 25 4
gpt4 key购买 nike

我正在尝试理解 java 中的正则表达式。我正在用 java 处理日志文件,因此我可以提取日志字段。例如,我有以下行:

Apr 10 21:08:55 kali sshd[37727]: Failed password for root from 127.0.0.1 port 42035 ssh2"

我想要这样的输出:

"Date&Time" = Apr 10 21:08:55
"Hostname" = kali
"Program Name" = sshd
"Log" = Failed password for root from 127.0.0.1 port 42035 ssh2

到目前为止,这是我的 java 代码:

公共(public)类 LogRegExp{

public static void main(String argv[]) {
String logEntryLine = "Apr 10 21:08:55 kali sshd[37727]: Failed password for root from 127.0.0.1 port 42035 ssh2";
String logEntryPattern = "(\\w.+) (\\d.+) (\\w.+) (\\w.+)";

Pattern p = Pattern.compile(logEntryPattern);
Matcher matcher = p.matcher(logEntryLine);
if (!matcher.matches()) {
System.err.println("Bad log entry (or problem with RE?):");
System.err.println(logEntryLine);
return;
}
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));

}

我试着按照这个例子:http://www.java2s.com/Code/Java/Development-Class/ParseanApachelogfilewithRegularExpressions.htm

但我无法使其适应我的需要。我了解如何应用转义字符、数字等,但我不知道如何根据我的情况进行调整。谁能帮帮我?

最佳答案

使用这段代码:

public class LogRegExp {

public static void main(String argv[]) {
String logEntryLine = "Apr 10 21:08:55 kali sshd[37727]: Failed password for root from 127.0.0.1 port 42035 ssh2";
String logEntryPattern = "([\\w]+\\s[\\d]+\\s[\\d:]+)\\s([\\w]+)\\s([\\w]+)\\[.+\\]:\\s(.+)";

Pattern p = Pattern.compile(logEntryPattern);
Matcher matcher = p.matcher(logEntryLine);
if (!matcher.matches()) {
System.err.println("Bad log entry (or problem with RE?):");
System.err.println(logEntryLine);
return;
}
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 - 如何在 Java 中使用 java.regex.Matcher 解析日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23010060/

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