これは、すべての3例の取るべき次のようになります。
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");
これは、間違ったデータが渡されたことを考慮していないことに注意してください。これは明らかに追加できますが、例がかなり乱雑になります。
興味のあるもの - なぜ正規表現ですか?名前 - >値マッピングのいくつかの小さな辞書を維持できますか? –