简体   繁体   中英

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;)

(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.

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})?$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM