Regex ^ \\d{4}-\\d{2}-\\d{2}$

Viewed 1849

I've to format a date into a specific format ^\\d{4}-\\d{2}-\\d{2}$. I'm searching now for a while and can't find a solution. I found these \\d{3}-\\d{4}, \d that nearly matches my requirements but I can't figure out why it doesn't match. I'm testing with regex101

As far I understand it, the first entry should work.

2021-11-10
"1234-12-34"

I also tried to copy characters from an Ascii-table to ensure they are not special.

2 Answers

Try to remove the ^ and the $

\\d{4}-\\d{2}-\\d{2}

^ matches the start of line and $ matches the end of line. So the second entry has " after the start and before the end, it doesn't match.

Depending on your language, no need to double backslashes (\\):

\d{4}-\d{2}-\d{2}

Doubling backslash is used for escaping purpose.

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

  1. It won't work with engines that don't understand the {} length atom (e.g. BSD grep without the -E flag).

  2. 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’
    
  3. Regular expressions are powerful, but they aren't always the right solution to every problem, especially if the problem is one of data validation.

Related