Regex Not Capturing Multiple Date Formats in Java - implementing Non-Greedy Matching
I've been banging my head against this for hours. I'm collaborating on a project where I'm trying to extract dates from a string that can have various formats like `MM/DD/YYYY`, `DD-MM-YYYY`, and `YYYY.MM.DD`. However, I'm working with issues where my regex seems to be overly greedy, leading to unexpected results. For example, given the string `"The events are on 12/31/2021, 01-01-2022, and 2022.02.15"`, I want to capture each date correctly. Hereβs the regex Iβve been using: ```java String regex = "(\d{2}[/-]\d{2}[/-]\d{4}|\d{4}[.]\d{2}[.]\d{2})"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); while (matcher.find()) { System.out.println(matcher.group()); } ``` The output I get is only the first date `12/31/2021`, and it fails to capture the others. I suspect it's because the alternation is not functioning as I intended. I've tried using lazy quantifiers and adjusting the order of the groups, but that just leads to capturing parts of the dates instead of whole ones. Iβm currently using Java 11. Any suggestions on how to modify my regex to capture all three date formats without missing any? Also, if there are any best practices for handling such scenarios, Iβd love to hear them!