Regex to capture groups in traceroute with Java8

Viewed 388

I am trying to parse traceroute results in Java8 using Regex.

I am using the below regex to identify the groups.

^(\\d*).*[AS(\\d*)]?\\s+([\\w+\\.]+)\\s+\\(([\\d+\\.]+)\\)[\\s+(\\d+\\.\\d+)\\s+ms]+

Some example lines that I need to parse are:

1  10.33.128.1 (10.33.128.1)  4.452 ms  3.459 ms  3.474 ms  
6  * [AS3356] 4.68.72.218 (4.68.72.218)  12.432 ms  11.819 ms  
 * 4.68.72.218 (4.68.72.218)  12.432 ms  11.819 ms  
  61.182.180.62 (61.182.180.62) 175.300 ms  203.001 ms

And I want to extract the hop number (if available), ASN (if available), hostname, IP and time

but with the above regex, it matches the strings 1,2, and 4 which is what I want but only gives me hop, host and ASN.

My code is like this:

Pattern hop_pattern = Pattern.compile(
        "^(\\d*).*[AS(\\d*)]?\\s+([\\w+\\.]+)\\s+\\(([\\d+\\.]+)\\)[\\s+(\\d+\\.\\d+)\\s+ms]+")
Matcher m = hop_pattern.matcher(target);

while(m.find()) {
    System.out.println("count: " + m.groupCount());
    for(int i = 1; i < m.groupCount() + 1; i++) {
        System.out.println(i + "->" + m.group(i));
    }
}

Some example lines that I need to parse are:

1 10.33.128.1 (10.33.128.1) 4.452 ms 3.459 ms 3.474 ms
6 * [AS3356] 4.68.72.218 (4.68.72.218) 12.432 ms 11.819 ms
* 4.68.72.218 (4.68.72.218) 12.432 ms 11.819 ms
61.182.180.62 (61.182.180.62) 175.300 ms 203.001 ms

And I want to extract the hop number (if available), ASN (if available), hostname, IP and time

but with the above regex, it matches the strings 1,2, and 4 which is what I want but only gives me hop, host and ASN.

My code is like this:

    Pattern hop_pattern = Pattern.compile(
            "^(\\d*).*[AS(\\d*)]?\\s+([\\w+\\.]+)\\s+\\(([\\d+\\.]+)\\)[\\s+(\\d+\\.\\d+)\\s+ms]+")
    Matcher m = hop_pattern.matcher(target);

    while(m.find()) {
        System.out.println("count: " + m.groupCount());
        for(int i = 1; i < m.groupCount() + 1; i++) {
            System.out.println(i + "->" + m.group(i));
        }
    }

I am not sure if something is wrong with the code or the regex itself. Thanks for help!

Update: Some examples and sample output

1 [AS0] 10.200.200.200 (10.200.200.200) 37.526 ms 35.793 ms 37.728 ms
Expected Output: hop: 1 asn: 0 hostname: 10.200.200.200 ip: 10.200.200.200 time: [37.526, 35.793, 37.728]

2 [AS0] scsc-usr-13500-02-eth1-07.xyz.com (10.96.15.3) 37.927 ms 36.122 ms *
Expected Output: hop: 2 asn: 0 hostname: scsc-usr-13500-02-eth1-07.xyz.com ip: 10.96.15.3 time: [37.927, 36.122]

I am not sure if something is wrong with the code or the regex itself. Thanks for help!

2 Answers
Related