Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to Match first 28 days of the month

Tags:

regex

asp.net

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

like image 670
Brian G Avatar asked Sep 08 '08 15:09

Brian G


People also ask

How to match a string with a valid date in regex?

Here are the details: The regex will match a string only if it contains at least one valid date, like: [dd-mm] Assuming the year in question is not a leap year. The number of days each month should have are: January 31 days February 28 days So on All text outside a valid date can be ignored, including other invalid dates.

How do you write a regular expression for a date?

A regular expression for dates (YYYY-MM-DD) should check for 4 digits at the front of the expression, followed by a hyphen, then a two-digit month between 01 and 12, followed by another hyphen, and finally a two-digit day between 01 and 31. Here’s the regex code that does all this: /^d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/

How do you find the month in a regex?

The month is matched by 0[1-9]|1[012], again enclosed by parentheses to keep the two options together. By using character classes, the first option matches a number between 01 and 09, and the second matches 10, 11 or 12. The last part of the regex consists of three options.

What is the regular expression for YYYY-MM-DD dates?

Regular Expression for YYYY-MM-DD Dates A date should start with a 4 digit year from 0000-9999. We can specify this using the following: /d {4}/


2 Answers

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.

like image 164
Simon Johnson Avatar answered Oct 01 '22 01:10

Simon Johnson


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.

like image 28
pilif Avatar answered Oct 01 '22 01:10

pilif