1
\$\begingroup\$

I have a string with date details with time, but I would like to show the day information alone. For that, I use the regexp to select the date. Can anyone tell me the regexp, and if what is used is the correct one?

Here is my string:

2014-09-12T00:00:00

Here is the regexp, what is used:

\d.+\-\d{1,2}

I am getting the result as:

2014-09-12

I am getting correct result, but I am wondering if there may be a better approach.

\$\endgroup\$
  • 1
    \$\begingroup\$ The logical answer to this question is "Do not use regex to parse a date, use the date library that comes with your language", but you do not provide enough context to even give the language. \$\endgroup\$ – rolfl Sep 25 '14 at 10:03
2
\$\begingroup\$

The regular expression you used, although it works, it's not very specific. It matches the sequence of these:

  • \d = a digit
  • .+ = one or more of any character
  • \- = a literal - (btw you didn't need the \ here, it has no effect here)
  • \d{1,2} = one or two digits

Many non-dates can match this pattern too, for example these strings:

  • 1abcdefg-4
  • 2999999!@$$#$@#$-12
  • ...

I would recommend to use a more strict pattern, for example:

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

This matches the sequence of these:

  • exactly 4 digits
  • literal -
  • exactly 2 digits
  • literal -
  • exactly 2 digits

Note that this is still not perfect. It won't prevent these invalid dates:

  • 2014-02-31
  • 9999-99-99

A bit more strict pattern would be:

2\d{3}-[01]\d-[0-3]\d

Which, of course, is still not perfect, because it will still allow 2014-19-39, for example. It's possible to be even more strict, but whether it's worth it / necessary or not depends on your use case.

| improve this answer | |
\$\endgroup\$

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