如何在java中搜索字符串以及前进的数字

时间:2014-07-17 04:20:49

标签: java string bufferedreader ping

我目前想知道如何搜索特定的字符串并查找继续执行的数字。我有一个程序,检查你输入的IP上的ping,它出来的最大,最小,平均等。我目前正试图看看是否有办法找到并打印出最大,最小和平均数字。我已经尝试过手动检查charAt但它最终会产生大约15行不必要的代码,而它应该只是少数几个。任何帮助将不胜感激。

这是我想要获得的数字的图片:

enter image description here

以下是我用来查找ping的代码

public static void runSystemCommand(String command, JTextArea field) {
    try {
        Process p = Runtime.getRuntime().exec(command);
        BufferedReader inputStream = new BufferedReader(
                new InputStreamReader(p.getInputStream()));

        String s = "";
        // reading output stream of the command
        while ((s = inputStream.readLine()) != null) {
            System.out.println(s);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

2 个答案:

答案 0 :(得分:2)

    String s = "Minimum: 672ms, Maximum: 696ms,...time=675ms ... ";
    // the following code will match the first two numbers but not the third! 
    Pattern p = Pattern.compile("\\s\\d+ms");
    Matcher m = p.matcher(s);
    while(m.find()) {
        System.out.println(m.group().trim());
    }

<强>输出

672ms
696ms

答案 1 :(得分:0)

您可以尝试以下策略:

  1. 用逗号分析行(可能添加结尾逗号)
  2. 解析=
  3. 上的每个结果段
  4. 通过修剪第一件来获得名称(最小/最大/。);通过解析第二个字符串获取整数时间,将字符串的一部分从0找到“ms”