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.
$ means "Match the end of the string" (the position after the last character in the string).
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).
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With