Date Format Patterns
You'll learn to write regular expressions that match common date formats like YYYY-MM-DD, MM/DD/YYYY, and ISO 8601.
Understanding Date Format Patterns
Dates come in many shapes: 2025-05-14, 05/14/2025, 14.05.2025, and more. Each format follows a predictable structure of digits and separators. Regular expressions excel at matching these patterns because dates are highly structured text.
Think of date formats like license plates—they follow strict rules about where numbers appear and what separators divide them. Your regex acts as a template checker.
Common Date Patterns
YYYY-MM-DD (ISO 8601)
Pattern isoDate = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
Matcher matcher = isoDate.matcher("2025-05-14");
if (matcher.matches()) {
System.out.println("Valid ISO date");
}
This pattern means: four digits, hyphen, two digits, hyphen, two digits.
MM/DD/YYYY (US Format)
Pattern usDate = Pattern.compile("\\d{2}/\\d{2}/\\d{4}");
if (usDate.matcher("05/14/2025").matches()) {
System.out.println("Valid US date");
}
Flexible Separators
Pattern flexDate = Pattern.compile("\\d{4}[-/.]\\d{2}[-/.]\\d{2}");
// Matches: 2025-05-14, 2025/05/14, or 2025.05.14
The character class [-/.] allows any of those three separators.
With Named Groups for Extraction
Pattern dateExtractor = Pattern.compile(
"(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})"
);
Matcher m = dateExtractor.matcher("Meeting on 2025-05-14");
if (m.find()) {
System.out.println("Year: " + m.group("year"));
System.out.println("Month: " + m.group("month"));
System.out.println("Day: " + m.group("day"));
}
Key Takeaway: Date patterns use \d{n} to specify digit counts and character classes for separators. Combine them with named groups to both validate format and extract date components for processing.