Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract date in a string C#?

What is the good solution for extracting a date which is given in a string?

For example:

string block = "This should try to get a date 2005-10-26"; //TODO! I WANT THE DATE

Any good tips for me?

Regex maybe?

like image 546
Khiem-Kim Ho Xuan Avatar asked Mar 23 '23 08:03

Khiem-Kim Ho Xuan


1 Answers

The simplest regex would be

new Regex(@"\b\d{4}-\d{2}-\d{2}\b")

but this doesn't do any error checking and only finds exactly that format.

If you want to do date validation, regex is not your best friend here. It's possible, but best left to a date parser, unless you want render suicidal whoever has to read your code six months from now. I would agree to a basic sanity check, but don't attempt to validate leap years etc.:

new Regex(@"\b\d{4}-(?:1[0-2]|0[1-9])-(?:3[01]|[12][0-9]|0[1-9])\b")
like image 162
Tim Pietzcker Avatar answered Apr 01 '23 07:04

Tim Pietzcker