2010-12-07 14 views
1

iが次の文字列を有する:正規表現を特定の文字列から取得する正規表現を作成するにはどうすればよいですか?

月:
Jan11
Feb11
Mar11
Apr11を

クォーター:
Q1 11
Q2 11
Q3 11
Q4 11
Q1 12


Cal_11
Cal_12
Cal_13

Iが表される各日付の先頭からDateTimeオブジェクトを作成するために正規表現を使用したいです文字列で。だから、Jan11は

new DateTime(2011,1,1) 

なり、Q2 11は

new DateTime(2011,4,1) 

だろうとCal_12は

new DateTime(2012,1,1). 
+0

興味のあるもの - なぜ正規表現ですか?名前 - >値マッピングのいくつかの小さな辞書を維持できますか? –

答えて

2

これは、すべての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"); 

これは、間違ったデータが渡されたことを考慮していないことに注意してください。これは明らかに追加できますが、例がかなり乱雑になります。

関連する問題