Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

regex

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.

like image 894
John Farrell Avatar asked Oct 15 '10 17:10

John Farrell


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

How do you match a space in regex?

If you're looking for a space, that would be " " (one space). If you're looking for one or more, it's " *" (that's two spaces and an asterisk) or " +" (one space and a plus).

Does regex match anything?

Matching a Single Character Using Regex ' dot character in a regular expression matches a single character without regard to what character it is. The matched character can be an alphabet, a number or, any special character.


2 Answers

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
like image 60
BrunoLM Avatar answered Nov 15 '22 12:11

BrunoLM


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);
like image 43
Klaus Byskov Pedersen Avatar answered Nov 15 '22 14:11

Klaus Byskov Pedersen