Using POSIX Character Classes
You don't mention a language, so I'm not sure why you're escaping your backslash characters. If you're looking for a portable solution, you can do this with POSIX character classes rather than the \d
atom which (while fairly common these days) is certainly not universal.
For example, this anchored expression:
^[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}$
will match with any extended regex engine I know, including egrep, pcregrep, Ruby, GNU awk, GNU sed (with the -r
flag), and others. As an example:
$ echo "2021-11-10" | egrep '^[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}$'
2021-11-10
Caveats
It won't work with engines that don't understand the {}
length atom (e.g. BSD grep without the -E
flag).
It will validate the format, but won't actually ensure that it's a valid date. For that, you need a tool that understands dates, such as GNU date. For example:
$ date -d '2021-11-10'
Wed Nov 10 00:00:00 EST 2021
$ date -d '1234-12-34'
date: invalid date ‘1234-12-34’
Regular expressions are powerful, but they aren't always the right solution to every problem, especially if the problem is one of data validation.