Extract date in a string C#?

2020-04-07 19:43发布

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?

1条回答
▲ chillily
2楼-- · 2020-04-07 20:38

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")
查看更多
登录 后发表回答