Hello,
I am trying to create a RegEx which validates dates in the following
format:
dd/mm/yyyy > 27/12/2007, 02/03/2006
d/m/yy > 1/4/97, 2/3/06
Basically:
- Day can be 1 to 31 or 01, 02 ... to 31.
- Month can be 1 to 12 or 01, 02 ... to 12
- Year can from 90, 91, ... or 1990, 1991, ...
The separators could be /.-
Does anyone knows a good Regex expression for this?
And am i thinking right about this?
Should I use year always with 4 numbers?
And can I set a minimum year to be accepted? Like 1920? Only dates
after 1920?
Thanks,
Miguel
Siva M - 08 Jun 2007 06:33 GMT
You might want to check www.regexlib.com
> Hello,
>
[quoted text clipped - 21 lines]
> Thanks,
> Miguel
Göran Andersson - 08 Jun 2007 08:30 GMT
> Hello,
>
[quoted text clipped - 21 lines]
> Thanks,
> Miguel
You could also look into DateTime.TryParseExact. It will try to parse a
date in a specific format, and tells you if it was a valid date or not.

Signature
Göran Andersson
_____
http://www.guffa.com
Alexey Smirnov - 08 Jun 2007 08:53 GMT
> Hello,
>
[quoted text clipped - 21 lines]
> Thanks,
> Miguel
something like this
Regex r = new Regex(@"(\d{1,2})/(\d{1,2})/(?<Year>(?:\d{4}|\d{2}))")
if(r.IsMatch(date_str))
{
string year = r.Match(date_str).Groups["Year"];
if (year.Length == 2 && Convert.ToInt32(year) >= 20) {
...date is correct
}
if (year.Length == 4 && Convert.ToInt32(year) >= 1920) {
...date is correct
}
}
I didn't test it, try it...
But I think it's better to convert it to the DateTime object, for
example with DateTime.TryParseExact as G?ran has suggested
Alexey Smirnov - 08 Jun 2007 08:56 GMT
> > Hello,
>
[quoted text clipped - 44 lines]
>
> - Show quoted text -
Wait, a silly typo.
(\d{1,2})/(\d{1,2})/(?<Year>\d{4}|\d{2})
Peter Bradley - 08 Jun 2007 10:35 GMT
Ysgrifennodd shapper:
> Hello,
>
[quoted text clipped - 21 lines]
> Thanks,
> Miguel
I'd check for a valid separator, then convert it to a DateTime and let
that check for validity using DateTime.Parse. Checking for the
separator's easy using a Regex. Something like:
(\d[/\.-]){3}
This will pick up on all the leap years and so forth.
As for setting a minimum year, you can do that when you convert the
string to a datetime - although you've made it a bit more difficult for
yourself by only using 2 digit dates in one of your formats (i.e. are
you going to allow 19? Does it mean 1919 or 2019?). So on a quick
first look I'd say you can only meaningfully do that for 4 digit dates.
HTH
Peter