Extract date in C # string?

What is a good solution to retrieve the date given in a string?

For instance:

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

Any good tips for me?

Maybe a regex?

+4
source share
1 answer

The simplest regular expression would be

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

but it does not do any error checking and only finds this particular format.

If you want to check the date, regex is not your best friend here. It is possible, but it is best to leave the date parser if you do not want the suicidal person to read your code in six months. I would agree to a basic sanity check, but I’m not trying to check leap years, etc .:

 new Regex(@"\b\d{4}-(?:1[0-2]|0[1-9])-(?:3[01]|[12][0-9]|0[1-9])\b") 
+7
source

Source: https://habr.com/ru/post/1489108/


All Articles