My attempt is [0-1][0-9]\\/[0-3][0-9]\\/[1-2][0-9]{3} but 13+ is not a month and neither is 31+ a day. Any help would be appreciated
-
4Don't use regex for that.Sotirios Delimanolis– Sotirios Delimanolis2014-03-28 00:27:08 +00:00Commented Mar 28, 2014 at 0:27
-
what should I use then? @SotiriosDelimanolisuser3002906– user30029062014-03-28 00:30:31 +00:00Commented Mar 28, 2014 at 0:30
-
A proper date parser.Sotirios Delimanolis– Sotirios Delimanolis2014-03-28 00:31:03 +00:00Commented Mar 28, 2014 at 0:31
-
I wrote a long answer about validating numeric ranges with regex. Not because it's a good idea, because it's not, rather because it's interesting from a learning regex point of view.aliteralmind– aliteralmind2014-03-28 21:19:35 +00:00Commented Mar 28, 2014 at 21:19
-
What @SotiriosDelimanolis says. See the good and modern answer by Basil Bourque.Anonymous– Anonymous2025-12-11 06:33:39 +00:00Commented 12 hours ago
3 Answers
Use a try/catch block where you extract the month and day, and then based on the parsed parameters, throw an illegalargument exception. Your situation definitely falls under the circumstances of when to throw such an exception as described here:
When should an IllegalArgumentException be thrown?
Thanks!
Comments
Two steps, one less problem1
Capture data which follows a specific format
The regular expression itself is then trivially
(\d{2})/(\d{2})/(\d{4})- the point is to check the format, not the validity, and capture the relevant data.Validate the captured data
int year = Integer.parse(m.groups(3)); // .. if (!validDate(year, month, day)) { .. }
Imagine how terrible it would be to try and also validate leap years with a regular expression alone; yet doing so with the above capture-validate is relatively trivial.
1 This is a (Y) answer, because it assumes that actual code is also allowed. However, the "real life" correct solution (Z) would be to use existing date parsing support in Java or Joda Time, etc.
Comments
tl;dr
Regex is overkill for that purpose.
Parse your input using LocalDate class with a DateTimeFormatter, trapping for DateTimeParseException to detect faulty input.
java.time
Java 8+ comes with industry-leading date-time classes found in the java.time packages.
For a date-only (year-month-day) value, use java.time.LocalDate class.
Specify a formatting pattern to match your expected input.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu" ) ;
Parse your input string as a LocalDate object. To detect faulty input, trap for DateTimeParseException.
try
{
LocalDate ld = LocalDate.parse( input , f ) ;
…
}
catch ( DateTimeParseException e )
{
… handle faulty input …
}