Search code examples
javascriptregexregular-language

Javascript regular expression for parsing information giving from PING command


I have a script that gets the output after a ping, the output looks like this:

var input = "PING localhost (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_req=1 ttl=64 time=0.065 ms
64 bytes from localhost (127.0.0.1): icmp_req=2 ttl=64 time=0.073 ms
64 bytes from localhost (127.0.0.1): icmp_req=3 ttl=64 time=0.065 ms

--- localhost ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2000ms
rtt min/avg/max/mdev = 0.065/0.067/0.073/0.010 ms"

I was first trying to get how many packets that was transmitted. So I tried with this regular expression: (\d+)*\spackets

Basically to match on the "NUMBER packets" it seems to work on this site: http://www.regular-expressions.info/javascriptexample.html but I can't replicate it.

And when using the regular expression with match, it also fails, like this:

"42 packets".match('(\d+)*\spackets');

Any ideas?


Solution

  • Javascript regex must be surrounded by forward slash delimiters to indicate a RegExp object, not quotes:

    "42 packets".match(/(\d+)\spackets/);
    

    Which is short form for:

    "42 packets".match(new RegExp('(\d+)\spackets'));