0

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

5
  • 4
    Don't use regex for that. Commented Mar 28, 2014 at 0:27
  • what should I use then? @SotiriosDelimanolis Commented Mar 28, 2014 at 0:30
  • A proper date parser. Commented 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. Commented Mar 28, 2014 at 21:19
  • What @SotiriosDelimanolis says. See the good and modern answer by Basil Bourque. Commented 12 hours ago

3 Answers 3

3

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!

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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 …
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.