1
\$\begingroup\$

I want to check if a given string is a date of the form YYYY-mm-dd, including all the steps in it, i.e. YYYY-mm-dd, YYYY-mm and YYYY.

For example, all of the following dates are valid:

2014

2014-07

2014-07-03

This is my current regex:

^\d{4}(:?-\d{1,2}(:?-\d{1,2})?)?$

Is it OK?

\$\endgroup\$
3
  • \$\begingroup\$ What language or framework is this regex used in? \$\endgroup\$
    – Reinderien
    Commented Feb 26, 2023 at 14:00
  • \$\begingroup\$ Why do you allow single-digit days and months? That doesn't match your description. \$\endgroup\$
    – Reinderien
    Commented Feb 26, 2023 at 14:01
  • \$\begingroup\$ @Reinderien JavaScript, oh they were just examples, single digits is also allowed \$\endgroup\$
    – pileup
    Commented Feb 26, 2023 at 16:33

1 Answer 1

1
\$\begingroup\$

Is it OK?

Yes.

In the sense that it is "correct". It matches your stated specification, as amended to include both single- and double-digit months and days.

Is it maintainable?

No, in a setting where multiple engineers who come and go will work on the code, it is less maintainable than this regex:

^\d{4}(-\d{1,2}){0,2}$

which in turn is less maintainable than this one:

^\d{4}(-\d{1,2})?(-\d{1,2})?$

Programs must be written for people to read, and only incidentally for machines to execute.

-- Abelson & Sussman, SICP

The last regex immediately conveys the notion of y-m-d to a newly hired engineer at a glance, in a way that the other formulations do not.

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.