.netregex

Regular Expression that Matches values for YYYYMM


I need some regular expression for .net that matches the following pattern: YYYYMM

Where:

I have done the below one the problem with this, is that it includes invalid month values.

[2]{1}[0]{1}[0-4]{1}[0-9]{1}[0-1]{1}[0-9]{1}

any suggestion?


Solution

  • This should work: 20[0-4]\d(0[1-9]|1[0-2])

    To match a month, you need to look for either:

    If you want want to capture the year and month, (20[0-4]\d)(0[1-9]|1[0-2])

    If you don't want to capture either year or month, 20[0-4]\d(?:0[1-9]|1[0-2])

    If you want to capture them with names, (?<year>20[0-4]\d)(?<month>0[1-9]|1[0-2])