I am looking for a Regular expression to match only if a date is in the first 28 days of the month. This is for my validator control in ASP.NET
I don't think this is a task very well-suited for a regexp.
I'd try and use the library functions (DateTime.Parse for .NET) to parse the date and then check the day component of it. Everything else is duplicating half the library function anyways.
Why not just covert it to a date data type and check the day? Using a regular expression, while it could be done, just makes it overly complicated.
Don't do this with Regex. Dates are formatted differently in different countries. Use the DateTime.TryParse routine instead:
DateTime parsedDate;
if ( DateTime.TryParse( dateString, out parsedDate) && parsedDate.Day <= 28 )
{
// logic goes here.
}
Regex is nearly the golden hammer of input validation, but in this instance, it's the wrong choice.
([1-9]|1\d|2[0-8]) // matches 1 to 28 but woudn't allow leading zeros for single digits
(0?[1-9]|1\d|2[0-8]) // matches 1 to 28 and would allow 01, 02,... 09
(where \d matches any digit, use [0-9] if your regex engine doesn't support it.)
See also the question What is the regex pattern for datetime (2008-09-01 12:35:45 ) ?
I would use one of the DateTime.TryParse techniques in conjunction with a CustomValidator