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

I need a regex to support date dd-MMM-yyyyand date formats dd-MMM.

Example:

04-Oct-2010
04-Oct
04-OCT-2010
04-OCT
0
source share
3 answers

Although you can check the format with a regular expression, it is very difficult (or even impossible) to check the date. To check the format, you can use:

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

If you only need a C # solution, there is a 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 can 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;)

+4
source

(, .)

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

, , 31-feb-2009.

Instead of regex, you can use a string DateTime.TryParse.

+1
source

All Articles