CodexBloom - Programming Q&A Platform

Regex guide with Date Format Validation in Java - Handling Different Separators and Formats

๐Ÿ‘€ Views: 3 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-05
regex java validation Java

I'm relatively new to this, so bear with me. I can't seem to get I've looked through the documentation and I'm still confused about I'm trying to validate date strings in Java using regex, but I'm working with issues when it comes to different formats and separators. My goal is to match dates in the formats `DD/MM/YYYY`, `MM-DD-YYYY`, and `YYYY.MM.DD`, but I want to allow flexible separators like `/`, `-`, or `.`. Hereโ€™s the regex pattern Iโ€™m currently using: ```java String regex = "^(\d{2}|\d{4}|\d{1,2})[/-](\d{1,2})[/-](\d{4}|\d{2})$"; ``` However, this pattern doesn't seem to work as expected. When testing it with strings like `12-04-2023` (which should match) and `2023/12/04` (which should also match), I get unexpected results. The regex fails to validate `2023.12.04`, even though it should. Additionally, dates like `31-06-2023` (an invalid date) are incorrectly validated. I've tried adjusting the regex to be more specific about the number of digits and the order, but I need to seem to get it right. For example, I need to ensure that the day and month are valid numbers (i.e., days want to exceed 31 and months want to exceed 12). Hereโ€™s a snippet of how Iโ€™m testing the regex: ```java import java.util.regex.*; public class DateValidator { public static void main(String[] args) { String[] testDates = {"12-04-2023", "2023/12/04", "31-06-2023", "2023.12.04"}; Pattern pattern = Pattern.compile(regex); for (String date : testDates) { Matcher matcher = pattern.matcher(date); System.out.println(date + " valid? " + matcher.matches()); } } } ``` Iโ€™m currently using Java 11 and need a regex solution that accommodates these variations while ensuring valid dates. Any help with improving my regex pattern or validating the date logic would be greatly appreciated! This is part of a larger API I'm building. Am I missing something obvious? Thanks in advance! I've been using Java for about a year now. Any ideas what could be causing this?