RegEx to match M/YYYY, MM/YYYY , M/YY or MM/YY format

后端 未结 4 1846
余生分开走
余生分开走 2020-12-31 12:43

Need help finding or having a RegEx match a MM/YY or MM/YYYY format. My RegExFu is weak and I\'m not even sure where to begin writing this.

Months should be 1-12, y

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-31 13:19

    Try:

    var re = new Regex(@"(?\d{2})/(?\d{2}|\d{4})");
    var month = re.Match(yourString).Groups["month"];
    ...
    

    An alternative is:

    if(dateStr.Length == 5)
        myDateTime = DateTime.ParseExact("MM/YY", dateStr);
    else
        myDateTime = DateTime.ParseExact("MM/YYYY", dateStr);
    

提交回复
热议问题