我有一个包含以下代码的日志文件...我想使用日志文件作为输入并过滤UserName,date并计算no。客户端断开连接,客户端连接和数据包丢弃对于每个用户名........ 记录样本:
[ComputerC7] UserName:ABC1 id:02 | (11/22/2016 01:20:03) | Client connected.
[ComputerC8] UserName:ABC2 id:01 | (11/24/2016 03:10:35) | Client disconnected.
[ComputerC9] UserName:ABC5 id:04 | (11/25/2016 01:20:35) | Packet drop.
[ComputerC7] UserName:ABC1 id:02 | (11/22/2016 01:20:03) | Packet drop.
我需要有唯一的列表用户。并分别显示每天的已连接,断开连接,数据包丢弃计数。这可能需要一些java代码和正则表达式。
输出:
UserName: ABC1 Date:11/22/2016 Connected :1 Disconnected :0 Packet Drop:1
UserName: ABC2 Date:11/24/2016 Connected :0 Disconnected :1 Packet Drop:0
UserName: ABC5 Date:11/25/2016 Connected :0 Disconnected :0 Packet Drop:1
答案 0 :(得分:2)
以下是您在SO中提出的第一个问题的完整答案。请确保您在将来的帖子中显示您尝试过的内容。
这是你需要尝试的正则表达式:
"UserName:([^\\s]*)(?:[^\\(]*)\\(([^\\s]*)[^\\|]*\\|\\s*([^\\.]*)"
要获得您想要的结果,您可以尝试以下方法。
package rejex;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author Maverick
*/
public class Starter {
public static HashMap<String, props> resultMap;
public static final String regex = "UserName:([^\\s]*)(?:[^\\(]*)\\(([^\\s]*)[^\\|]*\\|\\s*([^\\.]*)";
public static final String string = "[ComputerC7] UserName:ABC1 id:02 | (11/22/2016 01:20:03) | Client connected.\n\n"
+ "[ComputerC8] UserName:ABC2 id:01 | (11/24/2016 03:10:35) | Client disconnected.\n\n"
+ "[ComputerC9] UserName:ABC5 id:04 | (11/25/2016 01:20:35) | Packet drop.\n\n"
+ "[ComputerC7] UserName:ABC1 id:02 | (11/22/2016 01:20:03) | Packet drop.\n\n";
public static void main(String[] args) {
Starter starter = new Starter();
starter.process();
for (String key : resultMap.keySet()) {
System.out.print(key);
System.out.print(" Connected :" + resultMap.get(key).clientConnected);
System.out.print(" Disconnected :" + resultMap.get(key).clientDisconnected);
System.out.println(" Packet Drop :" + resultMap.get(key).packetDrop);
}
}
public void process() {
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
String key = "";
resultMap = new HashMap<String, props>();
while (matcher.find()) {
key = "UserName: " + matcher.group(1) + " Date:" + matcher.group(2);
if (resultMap.containsKey(key)) {
resultMap.put(key, resultMap.get(key).increment(matcher.group(3)));
} else {
resultMap.put(key, new props().increment(matcher.group(3)));
}
}
}
public class props {
int clientDisconnected;
int clientConnected;
int packetDrop;
public props increment(String val) {
if (val.contains("disconnected")) {
clientDisconnected += 1;
} else if (val.contains("connected")) {
clientConnected += 1;
} else if (val.contains("drop")) {
packetDrop += 1;
}
return this;
}
}
}