How to formulate a regex to get Dates from specific strings?
i have the following strings:
Months:
Jan11 Feb11 Mar11 Apr11 etc. Quarters: Q1 11 Q2 11 Q3 11 Q4 11 Q1 12 etc. Years Cal_11 Cal_12 Cal_13 etc.
I would like to use a regular expression to create a DateTime object starting at the beginning of each date represented by a string. So Jan11 would be
new DateTime(2011,1,1)
, Q2 11 would be
new DateTime(2011,4开发者_开发百科,1)
and Cal_12 would be
new DateTime(2012,1,1).
This should take of all three cases:
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;
}
Calling like this:
parse("Jan11");
parse("Q2 11");
parse("Cal_12");
Please note that this doesn't account for incorrect data passed in. This could be added obviously, but would make the example quite cluttered.
精彩评论