2009-10-07 25 views

回答

11

正則表達式可能會矯枉過正。只需拆分';',Trim(),並致電Date.Parse(...), 它甚至會爲您處理時區偏移量。

using System; 

namespace ConsoleImpersonate 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 

      string str = "\tid [email protected]; Tue, 6 Oct 2009 15:38:16 +0100"; 
      var trimmed = str.Split(';')[1].Trim(); 
      var x = DateTime.Parse(trimmed); 

     } 
    } 
} 
+1

這樣做 - 是obv認爲它比它更困難 - 謝謝! leddy – leddy 2009-10-07 16:14:40

+0

永遠記住偉大的傑米Zawinski:有些人,當遇到問題時,認爲「我知道,我會用正則表達式。」現在他們有兩個問題。 – 2011-08-21 16:53:22

3

你可以試試這個代碼(可能調整)

Regex regex = new Regex(
     ";(?<date>.+?)", 
    RegexOptions.IgnoreCase 
    | RegexOptions.CultureInvariant 
    | RegexOptions.IgnorePatternWhitespace 
    | RegexOptions.Compiled 
    ); 

var dt=DateTime.Parse(regex.Match(inputString).Groups["date"].Value) 
1

這裏有一個正則表達式的方法相匹配的格式。日期結果按照您的指定格式化。

string input = @"\tid [email protected]; Tue, 6 Oct 2009 15:38:16 +0100"; 
// to capture offset too, add "\s+\+\d+" at the end of the pattern below 
string pattern = @"[A-Z]+,\s+\d+\s+[A-Z]+\s+\d{4}\s+(?:\d+:){2}\d{2}"; 
Match match = Regex.Match(input, pattern, RegexOptions.IgnoreCase); 

if (match.Success) 
{ 
    string result = match.Value.Dump(); 
    DateTime parsedDateTime; 
    if (DateTime.TryParse(result, out parsedDateTime)) 
    { 
     // successful parse, date is now in parsedDateTime 
     Console.WriteLine(parsedDateTime.ToString("dd-MM-yyyy hh:mm:ss")); 
    } 
    else 
    { 
     // parse failed, throw exception 
    } 
} 
else 
{ 
    // match not found, do something, throw exception 
}