Java Quick RegEx Matching

Suppose you want to match something in Java such as the average time from a ping output:

Pinging steamr.com [64.22.123.253] with 32 bytes of data:
Reply from 64.22.123.253: bytes=32 time=100ms TTL=53
Reply from 64.22.123.253: bytes=32 time=100ms TTL=53
Reply from 64.22.123.253: bytes=32 time=101ms TTL=53
Reply from 64.22.123.253: bytes=32 time=100ms TTL=53

Ping statistics for 64.22.123.253:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 100ms, Maximum = 101ms, Average = 100ms

You would want to do something like:

Pattern pingPattern = Pattern.compile(".*Minimum = [0-9]+ms, Maximum = [0-9]+ms, Average = ([0-9]+)ms.*", Pattern.DOTALL);
Matcher pingMatch   = pingPattern.matcher(pingOutput);

if (pingMatch.matches()) {
	averagePing = Integer.parseInt(pingMatch.group(1));
}

Note that the ‘.’ in the pattern does not by default match new lines or return carriages. The Pattern.DOTALL is needed so that ‘.’ accepts everything. RTFM for more info.

Leave a Reply

Your email address will not be published.