I have a question about reluctant fetch strategy on regular expressions.
Given the following Java code:
Pattern datePattern = Pattern.compile("(.*?)(\\d\\d\\d\\d-\\d\\d-\\d\\d)(.*)");
Matcher matcher = datePattern.matcher("2017-03-16");
if(matcher.find()){
System.out.println("Matched");
String extractedDate = matcher.group(1);
System.out.println("Extracted date: " + extractedDate);
}
I get this output:
Matched
Extracted date:
So matcher.group(1) just extracts an empty string. It seems I don't understand how reluctant fetch strategy is really working. I had thought that the first defined group in the pattern:
(.*?)
will try to match as few characters as possible. In other words, when it can match something to the second group:
(\d\d\d\d-\d\d-\d\d)
then it will match it to that group and consume the first group with "nothing".
The third group should also have no effect in my opinion.
Can someone explain me why in the given example I don't get the expected string "2017-03-16" from matcher.group(1)?
Thank you