Regex scenarios to Validate Custom Date Formats in Java - implementing Grouping
I'm testing a new approach and I'm trying to validate a custom date format `dd/MM/yyyy` in a Java application using regex, but I'm working with issues with matching the date correctly. I want to ensure that the day can only have values between `01` and `31`, the month between `01` and `12`, and the year can be any four-digit number. My current regex looks like this: ```java String regex = "^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[0-2])/(\d{4})$"; ``` When I test it with the string `29/02/2023`, it returns `false`, which is unexpected since this is a valid date format. I've also tried other valid dates like `31/12/2022` and `15/06/2021`, which are correctly matched. The regex seems to work for most cases, but I suspect that the question lies in how I'm enforcing the day limits because it doesn't account for different month lengths or leap years. I have used the following code to test my regex: ```java String dateToTest = "29/02/2023"; boolean isValid = dateToTest.matches(regex); System.out.println(isValid); // Expected: true, Actual: false ``` I also checked the groups using the matcher: ```java Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(dateToTest); if (matcher.find()) { System.out.println("Day: " + matcher.group(1) + ", Month: " + matcher.group(2) + ", Year: " + matcher.group(3)); } else { System.out.println("No match found."); } ``` Is there a way to modify the regex to accommodate February's varying lengths and ensure it works correctly for leap years? Any suggestions would be greatly appreciated! Any suggestions would be helpful.