Extract groups with regex

2

I need to extract the session and date from the line below, the date I have separated with a dash and a bar.

The patterns work correctly individually but when I try to extract the two, nothing comes.

Pattern p = Pattern.compile("(\w{8}-\w{4}-\w{4}-\w{4}-\w{12}) (\d{2}/\d{2}/\d{4} | \d{4}-\d{2}-\d{2})");
Matcher m = p.matcher("{E4AE5831-548B-4429-CB99-2429334A6348} | 16/03/2017 00:59:35 | [ColetaCPFVerificaColetaInicialReportCode] : [O seguinte prompt será vocalizad");

    if(m.find()){
        System.out.println(m.group(1));
        System.out.println(m.group(2));
    }
    
asked by anonymous 20.03.2017 / 15:15

2 answers

1

The pattern should match all characters in the text.

  • Between the session and the date there is no space, but "} | " .
  • The two date alternatives should not have spaces between them: (data1|data2) .


Regular expression

^\{([\dA-F]{8}(?:-[\dA-F]{4}){4}[\dA-F]{8})} \| (\d{2}/\d{2}/\d{4}|\d{4}-\d{2}-\d{2})

Description


Code

import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "^\{([\dA-F]{8}(?:-[\dA-F]{4}){4}[\dA-F]{8})\} \| (\d{2}/\d{2}/\d{4}|\d{4}-\d{2}-\d{2})";
final String linha = "{E4AE5831-548B-4429-CB99-2429334A6348} | 16/03/2017 00:59:35 | [ColetaCPFVerificaColetaInicialReportCode] : [O seguinte prompt será vocalizad";

final Pattern p = Pattern.compile(regex);
final Matcher m = p.matcher(linha);

if(m.find()){
    System.out.println(m.group(1));
    System.out.println(m.group(2));
}

Result

E4AE5831-548B-4429-CB99-2429334A6348
16/03/2017

You can test here: link

    
26.03.2017 / 12:03
0

I was misreading the way the pattern works.

The solution was to inform the characters between the two groups that I want to extract by entering the quantifier

.*
Pattern p = Pattern.compile("(\w{8}-\w{4}-\w{4}-\w{4}-\w{12}).*(\d{2}/\d{2}/\d{4} | \d{4}-\d{2}-\d{2})");
Matcher m = p.matcher("{E4AE5831-548B-4429-CB99-2429334A6348} | 16/03/2017 00:59:35 | [ColetaCPFVerificaColetaInicialReportCode] : [O seguinte prompt será vocalizad");
if(m.find()){
    System.out.println(m.group(1));
    System.out.println(m.group(2));
}
    
20.03.2017 / 16:33