在C#中使用RegEx解析多个日期格式

big*_*mac 2 c# regex datetime

使用C#4.5我需要能够接受多种字符串格式的日期,并且需要能够将它们全部解析为有效日期.例子包括:

04-2014
April, 2014
April,2014
Run Code Online (Sandbox Code Playgroud)

我已经提出了以下代码,允许我配置一个字典,其中包含所有可能的格式及其代表性的RegEx格式和.NET等效格式DateTime.ParseExact.这个解决方案有效...然而,有很多foreachif块,我只是想知道是否有更优雅/干净/更快的解决方案.

DateTime actualDate;
var dateFormats = new Dictionary<string, string> { { @"\d{2}-\d{4}", "MM-yyyy" }, { @"(\w)+,\s\d{4}", "MMMM, yyyy" }, { @"(\w)+,\d{4}", "MMMM,yyyy" } };
var dateValues = new[] { "04-2014", "April, 2014", "April,2014", "Invalid Date" };
var successfulDateParse = false;
foreach (var dateValue in dateValues)
{
    foreach (var dateFormat in dateFormats)
    {
        var regex = new Regex(dateFormat.Key);
        var match = regex.Match(dateValue);
        if (match.Success)
        {
            actualDate = DateTime.ParseExact(match.Value, dateFormat.Value, CultureInfo.InvariantCulture);
            successfulDateParse = true;
            break;
        }
    }
    if (!successfulDateParse)
    {
        // Handle where the dateValue can't be parsed
    }
    // Do something with actualDate
}
Run Code Online (Sandbox Code Playgroud)

任何输入都表示赞赏!

EZI*_*EZI 6

你不需要正则表达式.您可以使用DateTime.TryParseExact

var dateValues = new[] { "04-2014", "April, 2014", "April,2014", "Invalid Date" };
var formats = new[] { "MM-yyyy","MMMM, yyyy","MMMM,yyyy" };

foreach (var s in dateValues)
{
    DateTime dt;
    if (DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt) == false)
    {
        Console.WriteLine("Can not parse {0}", s);
    }
}
Run Code Online (Sandbox Code Playgroud)