user3002906
user3002906

Reputation: 33

Cannot get date RegEx mm/dd/yyyy down in java

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

Upvotes: 0

Views: 207

Answers (2)

user2864740
user2864740

Reputation: 61885

Two steps, one less problem1

  1. 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.

  2. 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.

Upvotes: 1

user3470765
user3470765

Reputation: 83

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!

Upvotes: 3

Related Questions