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:


Here is the regexp, what is used:


I am getting the result as:


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


closed as unclear what you're asking by vnp, Vogel612, Kid Diamond, Heslacher, Gareth Rees Sep 25 '14 at 9:27

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 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

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:


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:


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.


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