我有以下字符串:
月:
Jan11
Feb11
Mar11
Apr11
等。
宿舍:
Q1 11
Q2 11
Q3 11
Q4 11
Q1 12
等。
年份
Cal_11
Cal_12
Cal_13
等。
我想使用一个正则表达式来创建一个DateTime对象,从每个日期的开头开始,每个日期都由一个字符串表示。所以Jan11会是
new DateTime(2011,1,1),Q2 11将是
new DateTime(2011,4,1)而Cal_12将会是
new DateTime(2012,1,1).发布于 2010-12-07 16:00:51
这应适用于所有三种情况:
DateTime? parse(string text)
{
Match m = Regex.Match(text, @"^(\w\w\w)(\d+)$");
if (m.Success)
{
return new DateTime(
2000 + Convert.ToInt32(m.Groups[2].Value),
1 + Array.IndexOf(CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedMonthNames, m.Groups[1].Value),
1);
}
m = Regex.Match(text, @"^Q(\d+) (\d+)$");
if (m.Success)
{
return new DateTime(
2000 + Convert.ToInt32(m.Groups[2].Value),
1 + 3 * (Convert.ToInt32(m.Groups[1].Value) - 1),
1);
}
m = Regex.Match(text, @"^Cal_(\d+)$");
if (m.Success)
{
return new DateTime(
2000 + Convert.ToInt32(m.Groups[1].Value),
1,
1);
}
return null;
}像这样打电话:
parse("Jan11");
parse("Q2 11");
parse("Cal_12");请注意,这并不说明传入的数据不正确。这显然是可以添加的,但会使示例变得非常混乱。
https://stackoverflow.com/questions/4378388
复制相似问题