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?
-
\$\begingroup\$ What language or framework is this regex used in? \$\endgroup\$Reinderien– Reinderien2023年02月26日 14:00:31 +00:00Commented Feb 26, 2023 at 14:00
-
\$\begingroup\$ Why do you allow single-digit days and months? That doesn't match your description. \$\endgroup\$Reinderien– Reinderien2023年02月26日 14:01:39 +00:00Commented Feb 26, 2023 at 14:01
-
\$\begingroup\$ @Reinderien JavaScript, oh they were just examples, single digits is also allowed \$\endgroup\$pileup– pileup2023年02月26日 16:33:28 +00:00Commented Feb 26, 2023 at 16:33
1 Answer 1
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.