java - 获取线路的特定部分

标签 java java.util.scanner

您好,我有一个包含跟踪路由和 ping 的日志文件。 我用

将它们分开
if (scanner.nextLine ().startsWith ("64 bytes"){}

所以我现在可以只使用 ping。

我对 ping 感兴趣的是 time=XX

示例数据行 =

64 bytes from ziva.zarnet.ac.zw (209.88.89.132): icmp_seq=119 ttl=46 time=199 ms

我一直在阅读其他人的类似问题,但我不知道如何应用到我的问题。

我实际上只需要数字,因为我将把它们放入 csv 文件中,这样我就可以制作数据图表。

编辑:使用 Robins 解决方案,我现在可以在屏幕上显示我的 ping,但它会执行其他所有操作并错过第一个。

 while (scanner.hasNextLine ()) {
   //take only pings.
   if (scanner.nextLine ().startsWith ("64 bytes")){
       String line = scanner.nextLine ();       
       String pingAsString = line.substring (line.lastIndexOf ("=") + 1, (line.length () - "ms".length ()));
       Double ping = Double.valueOf (pingAsString);
       System.out.println ("PING AS STRING = "+ping);
   }
}

已排序。那只是需要移动线路分配。大写字母。但说清楚了。 :D

最佳答案

尝试使用 RegularExpression提取您需要的数据:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegExTest {
    public static void main(String[] args) {
        String test = "line= 14103 64 bytes from ziva.zarnet.ac.zw (209.88.89.132): icmp_seq=119 ttl=46 time=199 ms";

        // build the regular expression string
        String regex = ".*time=(\\d+).*";

        // compile the regular expresion into a Pattern we can use on the test string
        Pattern pattern = Pattern.compile(regex);

        Matcher matcher = pattern.matcher(test);

        // if the regular expression matches, grab the value matching the
        // expression in the first set of parentheses: "(\d+)"
        if (matcher.matches()) {
            System.out.println(matcher.group(1));
        }
    }
}

关于java - 获取线路的特定部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9853511/

相关文章:

java - 如何解析具有继承项的 Json 泛型数组

java - getText().toString() 常量和资源类型不匹配

java - 当 JTable 中的表失去焦点时,如何取消选择行?

java - 尝试允许用户使用扫描仪选择文本文件

java - 使用 Scanner 库和 if 语句,简单的任务吗?

java - Guava 重试器调用函数直到发生异常

java - 与特定浏览器通信

java - 使用扫描仪读取同一行两次

java - 需要捕获 IOException 和异常

java - 将一行中的所有整数扫描到 ArrayList 中