2009-10-07 26 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 
}