开发者

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

开发者 https://www.devze.com 2023-01-20 07:45 出处:网络
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.

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, years, well anything beyond 2009 should be valid. Sorry for not mentioning more details before. This is used as an expiration date.

I'll add a bounty for whomever goes above and beyond and validates MM/YY or MM/YYYY format that is >= today's date. No sense letting expired stuff past the first validation layer.


I feel bad since I changed my requirements and had to be more specific in what I needed mid-question so I'll award bounties to all those who answered once the no-bounty window expires.


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


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


Try this:

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

Constrains to one and two-digit months (01-12, 1-12) and two and four years (00-99, 1900-2199).


@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

精彩评论

暂无评论...
验证码 换一张
取 消