簡體   English   中英

dd-MMM-yyyy和dd-MMM的正則表達式?

[英]Regular Expression for dd-MMM-yyyy and dd-MMM?

我需要一個正則表達式來支持兩種日期格式dd-MMM-yyyydd-MMM

例如:

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

如果只需要C#解決方案,那么還有更優雅的解決方案:

//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());
}

此代碼打印:

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

您甚至可以使用一些漂亮的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();
}

而且我們有相同的結果;)

(確保打開不區分大小寫的修飾符。)

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

請注意,這不會檢查無效日期,例如31-feb-2009

代替正則表達式,您可以將字符串輸入DateTime.TryParse方法中。

盡管您可以使用正則表達式驗證格式,但很難(甚至不可能)驗證日期本身。 要驗證格式,可以使用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM