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

- 122,468
- 25
- 185
- 269

- 33
- 5
-
2Don't use regex for that. – Sotirios Delimanolis Mar 28 '14 at 00:27
-
what should I use then? @SotiriosDelimanolis – user3002906 Mar 28 '14 at 00:30
-
A proper date parser. – Sotirios Delimanolis Mar 28 '14 at 00:31
-
I wrote a [long answer](http://stackoverflow.com/a/22702401/2736496) 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 Mar 28 '14 at 21:19
2 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!

- 1
- 1

- 83
- 5
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.

- 60,010
- 15
- 145
- 220