2016-08-13 26 views
0

從這:的grep平輸出,只顯示延遲使用JavaScript

PING google.com (74.125.68.138) 56(84) bytes of data. 
64 bytes from sc-in-f138.1e100.net (74.125.68.138): icmp_seq=1 ttl=48 time=76.8 ms 
64 bytes from sc-in-f138.1e100.net (74.125.68.138): icmp_seq=2 ttl=48 time=86.8 ms 

我需要使用javascript這部分分開:

76.8 
86.8 

到目前爲止,我想出了這一點:

'([0-9][0-9][0-9].[0-9] ms|[0-9][0-9].[0-9] ms|[0-9].[0-9] ms)' 

但是,當延遲達​​到2位以上時,它似乎無法正常工作。

回答

1

您可以使用:

/time=(\d+(\.\d+)?) ms$/ // 1: one digit or more 
     \_/\______/  // 2: optionally followed by a dot and one digit or more 
     1  2   // $: end of input 

var ping = 
 
    "64 bytes from sc-in-f138.1e100.net (74.125.68.138): icmp_seq=1 ttl=48 time=76.8 ms"; 
 

 
var time = Number(ping.match(/time=(\d+(\.\d+)?) ms$/)[1]); 
 

 
console.log(time);

+0

非常感謝這個漂亮的解釋。我真的應該花一些時間學習正則表達式。 – bran

+1

很高興幫助! [MDN文檔](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)是一個很好的開始。 – Arnauld

+0

我發佈了一個新的問題,這與此有點相關。如果你有興趣,你可以看看嗎? http://stackoverflow.com/questions/38936419/capturing-websocketd-output-with-smoothie-charts – bran