在字符串C#中提取日期? [英] Extract date in a string C#?

查看:89
本文介绍了在字符串C#中提取日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提取字符串中提供的日期的好方法是什么?



例如:



string block =This should try to get a date 2005-10-26;
// TODO!我想要日期



对我有好的提示?



正则表达式可能吗?

解决方案

最简单的正则表达式将是

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

但是,这并不会进行任何错误检查,只能找到



如果要进行日期验证,正则表达式不是您最好的朋友。这是可能的,但最好留给一个日期解析器,除非你想在现在六个月之后呈现自杀的谁必须阅读你的代码。我同意基本的理智检查,但不要尝试验证闰年等:

 新的正则表达式(@ \b\d {4}  - (?: 1 [0-2] | 0 [1-9]) - (?:3 [01] | [12] [0-9] | 0 [1-9 ])\b)


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?

解决方案

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")

这篇关于在字符串C#中提取日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆