Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex extract capture group if it exists

Tags:

java

regex

I apparently don't understand Java's regex library or regex either for that matter.

for this string:

String text = "asdf 2013-05-12 asdf";

this regex explodes in my face:

String REGEX_FORMAT_1 = ".+?([0-9]{4}\\s?-\\s?[0-9]{2}\\s?-\\s?[0-9]{2}).+";

Matcher matcher_1 = PATTERN_FORMAT_1.matcher(text);
if(matcher_1.matches()) {
    String matchedGroup = matcher_1.group();
    ...
}     

Semantically this makes sense to me but it seems I've totally misunderstood something. The regex works fine in some online regex editors like regex101 but not in others. Could someone please help me understand why I don't get the capture group containing 2013-05-12 ...

like image 993
magnusson Avatar asked Jul 26 '26 17:07

magnusson


1 Answers

group() is equivalent to group(0) and returns the entire matched string. Use group(1) to pull out the first matched group.

String  text    = "asdf 2013-05-12 asdf";
String  regex   = ".+?([0-9]{4}\\s?-\\s?[0-9]{2}\\s?-\\s?[0-9]{2}).+";
Matcher matcher = Pattern.compile(regex).matcher(text);

if (matcher.matches()) {
    String matchedGroup = matcher.group(1);
    System.out.println(matchedGroup);
}

Output:

2013-05-12
like image 87
John Kugelman Avatar answered Jul 28 '26 07:07

John Kugelman