我正在努力从ping响应中读取数据,如下所示,这是我们应用程序中的一个api返回的。
"PING 2001:0558:4070:0071:021D:D4FF:FEB3:1F0B (2001:558:4070:71:21d:d4ff:feb3:1f0b): 64 data bytes
72 bytes from 2001:558:4070:71:21d:d4ff:feb3:1f0b: icmp_seq=0. time=11.7 ms
72 bytes from 2001:558:4070:71:21d:d4ff:feb3:1f0b: icmp_seq=1. time=12.1 ms
<p />
2001:0558:4070:0071:021D:D4FF:FEB3:1F0B PING Statistics----
2 packets transmitted, 2 packets received, 0% packet loss
round-trip (ms) min/avg/max/stddev = 11.7/11.9/12.1/0.32"
我需要一个正则表达式模式匹配器来获取
List<Double> times = [11.7, 12.1]
int transmitted = 2
int received = 2
double loss = 0;
double min=11.7
double avg=11.9
double max=12.1
double stddev=0.32
我一直在工作,但可以获得一个我可以匹配所有内容的RE
Pattern re = Pattern.compile( "(.*) = (.+?)/(.+?)/(.+?)/(.*)",
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
答案 0 :(得分:2)
试试这个。
String s = ""
+ "PING 2001:0558:4070:0071:021D:D4FF:FEB3:1F0B (2001:558:4070:71:21d:d4ff:feb3:1f0b): 64 data bytes\n"
+ "72 bytes from 2001:558:4070:71:21d:d4ff:feb3:1f0b: icmp_seq=0. time=11.7 ms\n"
+ "72 bytes from 2001:558:4070:71:21d:d4ff:feb3:1f0b: icmp_seq=1. time=12.1 ms\n"
+ "<p />\n"
+ "2001:0558:4070:0071:021D:D4FF:FEB3:1F0B PING Statistics----\n"
+ "2 packets transmitted, 2 packets received, 0% packet loss\n"
+ "round-trip (ms) min/avg/max/stddev = 11.7/11.9/12.1/0.32\n";
Pattern PAT_TIME = Pattern.compile("time=(?<TIME>\\d+.\\d+)\\s+ms");
Pattern PAT_REST = Pattern.compile(
"(?<TRANSMITTED>\\d+)\\s+packets transmitted.*"
+ "(?<RECEIVED>\\d+)\\s+(packets )?received.*"
+ "(?<LOSS>\\d+)% packet loss.*" + "min/avg/max/(stddev|mdev)\\s+=\\s+"
+ "(?<MIN>\\d+\\.\\d+)/"
+ "(?<AVG>\\d+\\.\\d+)/"
+ "(?<MAX>\\d+\\.\\d+)/"
+ "(?<STDDEV>\\d+\\.\\d+)",
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
List<Double> times = new ArrayList<>();
Matcher m1 = PAT_TIME.matcher(s);
while (m1.find())
times.add(Double.parseDouble(m1.group("TIME")));
Matcher m2 = PAT_REST.matcher(s);
m2.find();
int transmitted = Integer.parseInt(m2.group("TRANSMITTED"));
int received = Integer.parseInt(m2.group("RECEIVED"));
double loss = Double.parseDouble(m2.group("LOSS"));
double min = Double.parseDouble(m2.group("MIN"));
double avg = Double.parseDouble(m2.group("AVG"));
double max = Double.parseDouble(m2.group("MAX"));
double stddev = Double.parseDouble(m2.group("STDDEV"));
System.out.printf("times=%s transmitted=%d received=%d loss=%f min=%f avg=%f max=%f stddev=%f%n",
times, transmitted, received, loss, min, avg, max, stddev);
输出
times=[11.7, 12.1] transmitted=2 received=2 loss=0.00000 min=11.7000 avg=11.9000 max=12.1000 stddev=0.320000