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

后端 未结 4 1826
余生分开走
余生分开走 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:02

    What about

    ^(1[0-2]|0[1-9]|\d)\/(20\d{2}|19\d{2}|0(?!0)\d|[1-9]\d)$
    

    Matches months

    // 10 to 12 | 01 to 09 | 1 to 9
    (1[0-2]|0[1-9]|\d)
    

    And years

    // 2000 to 2099 | 1900 to 1999
    // 01 to 09 | 10 to 99
    (20\d{2}|19\d{2}|0(?!0)\d|[1-9]\d)
    

    To match anything >= 2010

    /^(1[0-2]|0[1-9]|\d)\/([2-9]\d[1-9]\d|[1-9]\d)$/;
    

    Result:

    12/2009 : false
    1/2010  : true
    12/2011 : true
    12/9011 : true
    12/07   : false
    12/17   : true
    
    0 讨论(0)
  • 2020-12-31 13:14

    Try this:

    ^(0[1-9]|1[0-2])/(19|2[0-1])\d{2}$
    

    Constrains to actual months (1-12) and years 1900-2199.

    0 讨论(0)
  • 2020-12-31 13:19

    Try:

    var re = new Regex(@"(?<month>\d{2})/(?<year>\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);
    
    0 讨论(0)
  • 2020-12-31 13:27

    @BrunoLM,

    ^(1[0-2]|0[1-9]|\d)\/(20\d{2}|19\d{2}|0(?!0)\d|[1-9]\d)$
    

    matches "0/2009". May I suggest a minor improvement:

    ^(1[0-2]|0[1-9]|[1-9])\/(20\d{2}|19\d{2}|0(?!0)\d|[1-9]\d)$
    
    0 讨论(0)
提交回复
热议问题