Regex for Validating Custom Date Formats in Java - implementing Leap Years
I've been working on this all day and I'm integrating two systems and I tried several approaches but none seem to work. This might be a silly question, but I've been struggling with this for a few days now and could really use some help... I'm trying to create a regex pattern to validate a specific date format in Java, which is `dd-MM-yyyy`. The scenario I'm working with is ensuring that the regex properly accounts for leap years. For instance, the date `29-02-2020` should be valid, but `29-02-2021` should not. My current regex is `^(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[0-2])-(\d{4})$`, but it doesn't handle the leap year logic correctly. I've tried breaking down the regex and implementing some conditions, but it gets quite complicated and messy. Here's a simplified version of what I've attempted: ```java String regex = "^(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[0-2])-(\d{4})$"; Pattern pattern = Pattern.compile(regex); "29-02-2020".matches(pattern); ``` While this works for basic validation, how can I incorporate a check for leap years? I looked into using a more complex regex, but it seems impractical. Additionally, I'm concerned about performance since this validation will be used frequently in a web application built on Spring Boot (version 2.5.4). Any advice on how to achieve this without overcomplicating my regex would be greatly appreciated. Would it be better to validate the format with regex and then use a date library for the leap year check, or is there a clean regex solution? My current approach has led me to unexpected results, like accepting invalid dates such as `31-04-2021` as valid, which is another scenario I need to address. I'm working on a application that needs to handle this. Has anyone else encountered this? I'm developing on Ubuntu 22.04 with Java. I'm on CentOS using the latest version of Java. This is my first time working with Java 3.9. Thanks for taking the time to read this!