tags:

views:

73

answers:

5

Need to match date in a user submitted string it should work with these different formats

jan 1 2000
january 1 2000
jan. 1 2000
1/1/2000
2000
january

how would you write this regular expression?

+5  A: 

I wouldn't use a RegExp for it:

DateTime attempt;
if (DateTime.TryParse(inputDate, out attempt)
{
  // You're good to go.
}

But that would struggle with "dates" of "January" or "2000".

Zhaph - Ben Duguid
how do i write a regex that matches a 4 digit number that is between 1000-9999
newU
MBO beat me to it in the comments to your question - however if you're accepting a year of 1000, why not 850? Or 55BC?
Zhaph - Ben Duguid
+1  A: 

Have you took a look at DateTime.TryParse first? Probably it will save you from using regex, except for maybe some special cases.

Konamiman
+1  A: 

I thing is too complicated to validate that with a regex.

Better use DateTime.TryParse

Also it is really hard to validate the date with regex because of the 31/30/29/28 days/month and of special cases like September 1752.

Victor Hurdugaci
+2  A: 

Even if these were the only allowed formats, it would be hard to do it with regex as it involves checking if the month names are valid, checking if the date is valid for the given month (April 31st etc), leap years etc.

Use the DateTime classes as others suggested.

Amarghosh
+1  A: 

Is this for a win or web application? If for windows simply use DateTime.TryParse but if it's for web then use javascript instead.

For javascript see this post

S M Kamran