1
votes

I'm trying to use a java regex to extract data. Its matching my data, but I can't get the group data. I'm trying to get the data 1, xmlAggregator, 268803451, 3. Looking at the docs, I assume that if I put() around \d+, and \w+, I get the numbers and strings inside the group. Any suggestions on how to change the regex?

String:

Span(trace_id:1, name:XmlAggregator, id:268803451, parent_id:3)

Java code:

      String pattern="Span\\(trace_id:(\\d+), name:(\\w+), id:(\\d+), parent_id:(\\d+), (duration:(\\d+))*";
      Pattern r = Pattern.compile(pattern);
      Matcher m = r.matcher(line);

      int count = 0;

      while(m.find()) {
         System.out.println("Match number "+count);
         System.out.println("start(): "+m.start());
         System.out.println("end(): "+m.end());
         System.out.println("Found value: " + m.group(count) );
         count++;
      }

Output:

Match number 0
start(): 0
end(): 64
Found value: Span(trace_id:1, name:XmlAggregator, id:268803451, parent_id:3, 

Hoping to get:

   
Found value: 1 
Found value: XmlAggregator 
Found value: 268803451 
Found value: 3 
2
And what is the expected output? - Amal Murali
Found value: 1 \n Found value: XmlAggregator \n Found value: 268803451 \n Found value: 3 \n - Arun
Please edit your question and add it. - Amal Murali
You should probably change the end of your pattern from )* to just \\). I think you should get rid of the start I don't think you want to match multiple spans at the same time (that' what your loop would be for), and it's probably a good idea to escape the closing parenthesis since it matches a literal. - DaoWen
Thanks DaoWen! That helps - Arun

2 Answers

2
votes

Each value is inside a group. Therefore you can loop over the number of groups matched and for each one print the group number, value, start index, etc.:

if(m.find()) {
    for(int count = 1; count <= m.groupCount(); count++) {
        System.out.println("Match number " + count);
        System.out.println("start(): " + m.start(count));
        System.out.println("end(): " + m.end(count));
        System.out.println("Found value: " + m.group(count));
    }
}
4
votes

You can access the capture groups (the parts of the match inside your unescaped parentheses) using the group method on your match result:

System.out.println("Trace ID = " + m.group(1));
System.out.println("Name = " + m.group(2));
// etc...

Note that you start counting the capture groups from 1, not 0. This is because group 0 corresponds to the entire matched string.