String Manipulation:从java中的字符串中取出数字?

时间:2012-10-23 18:40:20

标签: java string ping

我希望能够从数字等字符串中提取某些内容,在速度和准确度方面执行此操作的最有效方法是什么?

例如,如果我有一个文件:PingFile.txt,其内容只是管道服务器的ping,如:

PING google.com (74.125.224.46): 56 data bytes
64 bytes from 74.125.224.46: icmp_seq=0 ttl=45 time=5.134 ms
64 bytes from 74.125.224.46: icmp_seq=1 ttl=45 time=5.102 ms
64 bytes from 74.125.224.46: icmp_seq=2 ttl=45 time=5.062 ms
64 bytes from 74.125.224.46: icmp_seq=3 ttl=45 time=4.988 ms
64 bytes from 74.125.224.46: icmp_seq=4 ttl=45 time=5.368 ms
64 bytes from 74.125.224.46: icmp_seq=5 ttl=45 time=5.012 ms

如果我只想提取时间值(5.134,5.102,5.062等),然后解析浮点数或双精度数而不是它们的字符串。我该怎么做?

谢谢,

Euden

3 个答案:

答案 0 :(得分:1)

我认为您可以使用regex="time=[0-9\\.]+"查找字符串time=5.134time=5.102

然后将子字符串作为"time=5.134".substring(5)来获取数字部分。

以下代码示例:

String timeString = "64 bytes from 74.125.224.46: icmp_seq=0 ttl=45 time=5.134 ms";
Pattern timePattern = Pattern.compile("time=[0-9\\.]+");
Matcher timeMatcher = timePattern.matcher(timeString);
if(timeMatcher.find()){
    String timeS = timeMatcher.group(0);
    System.out.println(timeS);
    String time = timeS.substring(5);
    System.out.println(time);
    double t = Double.parseDouble(time);
    System.out.println(t);
}

答案 1 :(得分:0)

您可以为每一行执行此操作:

String[] tokens = line.split(" ");
String timeString = tokens[tokens.length-2];
float time = Float.parseFloat(timeString);

如果需要,您可以使用BufferedReader逐行读取。

答案 2 :(得分:0)

有很多方法可以做到,比如......

  • 使用Pattern类,但这可能是你想要的重量级
  • 使用Scanner类,虽然这可能仍然超出您的需要
  • 使用string.split(“”)[6]和Float.valueOf()(或Double.valueOf())

我确信还有其他方法可以做到。

相关问题