tags:

views:

665

answers:

6

Does anyone have any ideas on if/how one could create a regular expression to match a date in any given period?

Two examples:

23/11/2008 - 12/04/2010

//The expression would evaluate whether 16/04/2010 was in this range, and return false.
//The expression would determine whether 03/12/2009 was in this range, and return true.

and

01/09/1984 - 30/04/2001

//The expression would evaluate whether 16/04/1990 was in this range, and return true.
//The expression would determine whether 03/12/2009 was in this range, and return false.

I've been racking my brain on how to come up with something, but I've got nothing that comes close. Examples on the web are only interested in checking whether a date is in a particular format, but nothing about validating ranges.

The reason I tagged C# in this is because, this couldn't be done in straight regex, and the range regex would need to be built manually for each individual case.

+14  A: 

Wouldn't it be easier to parse the strings to DateTimes and comparing those?

Joren
Well, I'm looking at creating the regex for each range once, and not every time. Yes, it could be easier I suppose... :)
Dan Atkinson
+6  A: 

I don't think you should regular expressions for range checks. First check whether the date is valid with a regular expression, then check whether it falls in the given period.

Eric Minkes
+3  A: 

DONT...

Use a regular expression to extract the date, and then compare it vs the range. This will be a LOT easier then creating a regexp to match a daterange...

This is a classic example for the famous "... and then you have 2 Problems" quote ;)

Heiko Hatzfeld
A: 

To my best knowledge it's not possible to do this. You can try a 2 steps approach: - regexp to find a date and store it in a date object - test if the found date is in your range

MariusCC
+2  A: 

It would be possible, but it would be a bit complicated to write code that generates a regular expression dynamically.

For the range 23/11/2008 - 12/04/2010 you would first divide it onto three ranges for the first year, last year and years between. Then you would divide each year into the months with the same number of days in them. Then you divide the date ranges for each month length into tens (e.g. 01-09, 10-19, 20-28). From that you can create a regular expression like:

^(2[3-9]|30)/11/2008|
(0[1-9]|[12]\d|3[01])/12/2008|
(0[1-9}|1\d|2[0-8])/02/2009|
(0[1-9]|[12]\d|3[01])/(0[13578]|1[02])/2009|
(0[1-9]|[12]\d|30)/(0[469]|11)/2009|
(0[1-9}|1\d|2[0-8])/02/2010|
(0[1-9]|[12]\d|3[01])/0[13]/2010|
(0[1-9]|1[0-2])/04/2010$
Guffa
A: 

Take a look at DateTime.ParseExact to turn the string into a date and then use them as regular DateTime ranges. The regex will be awful if possible!!

xoxo