开发者

Regular Expression for dd-MMM-yyyy and dd-MMM?

I need a regular expression for 开发者_运维知识库support both date formats dd-MMM-yyyy and dd-MMM.

Ex:

04-Oct-2010
04-Oct
04-OCT-2010
04-OCT


If you need only C# solution, there is much more elegant solution:

//I intentionally change to 5th of October
var stringDates = new string[] { "05-Oct-2010", "05-Oct", "05-OCT-2010", "05-OCT" };
foreach(var s in stringDates)
{
    DateTime dt;

    if (DateTime.TryParseExact(s, new string[] { "dd-MMM-yyyy", "dd-MMM" }, null, DateTimeStyles.None, out dt) )
        Console.WriteLine(dt.ToShortDateString());
}

This code prints:

05/10/2010
05/10/2010
05/10/2010
05/10/2010

And you could even use some fancy LINQ:

static DateTime? Parse(string str, string[] patterns)
{
    DateTime result;
    if (DateTime.TryParseExact(str, patterns, null, DateTimeStyles.None, out result) )
        return result;
    return null;
}

static void Main(string[] args)
{
    var stringDates = new string[] { "05-Oct-2010", "05-Oct", "05-OCT-2010", "05-OCT" };
    var patterns = new string[] {"dd-MMM-yyyy", "dd-MMM"};
    var dates = from s in stringDates
                let dt = Parse(s, patterns)
                where dt.HasValue
                select dt.Value;

    foreach( var d in dates)
        Console.WriteLine(d.ToShortDateString());

    Console.ReadLine();
}

And we have the same result;)


Although you could validate the format using a regex, it's very hard (or even impossible) to validate the date itself. To validate the format, you could use:

 ^\d\d-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)(-\d{4})?$


(Make sure you turn on the case-insensitive modifier.)

^([012]\d|3[01])-(jan|feb|ma[ry]|apr|ju[nl]|aug|sept?|oct|nov|dec)(?:-(\d{4}))?$

Note that this will not check for invalid dates like 31-feb-2009.

Instead of regex, you could feed the string into the DateTime.TryParse method instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜