我目前想知道如何搜索特定字符串并查找其后面的数字。我有一个程序可以检查您输入的 ip 上的 ping,并显示最大、最小、平均值等。我目前正在尝试查看是否有一种方法可以查找并打印出最大、最小和平均数字。我尝试过手动检查 charAt,但最终却出现了大约 15 行不必要的代码,而实际上应该只有几行。任何帮助将不胜感激。
这是我想要获取的数字的图片:
这是我用来查找 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();
}
}
最佳答案
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
关于java - 如何在java中搜索字符串及其后面的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24794832/