tags:

views:

73

answers:

6

anybody can help me with a regex for Date in this format dd.MM.yyyy

I want to use it with a dataannotation like this

[RegularExpression(@"theregex")]
public DateTime Date {get;set;}
A: 
^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$ 

This one also accepts - and / as separators. You can remove them if you want.

Matteo Mosca
A: 

did you try:

\(\d{2}\.[01]\d{1}\.\d{4}\)
John Weldon
I don't think this one is good. The first portion accepts anything from 00 to 99, and we know that the day portion must can't be greater than 31. Also the secondo portions accepts antyhing from 00 to 19 and the highest month is 12.
Matteo Mosca
True, it's just a fast match regex, something more robust could be found by googling, or thinking through variations.
John Weldon
A: 
[0-3]{0,1}[0-9]\.[0-1]{0,1}[0-9]\.[0-9]{4,2}

matches: 28.2.96, 1.11.2008 and 12.10.2005

M3t0r
+2  A: 
^(0[1-9]|[12][0-9]|3[01])[.](0[1-9]|1[012])[.](19|20)[0-9]{2}$

This regex matches 01.01.1900, 01.01.2000 but doesn't match 1.1.2000 or 1/1/00.

madgnome
you could at least make the 0's optional... it also doesn't match 31.01.2000 :(
Ian
Surely it will match 31.01.2000?
Chris
31.01.2000 is match.
madgnome
But it will break in the next millennium :-)
JLWarlow
+4  A: 

I suggest that regex is not exactly the best way to do this. You haven't given the context, so it's hard to guess what you're doing overall... but you might want to create a DateExpression attribute or such and then do:

return DateTime.ParseExact(value, "dd.MM.yyyy");

in wherever your converter is defined.

Noldorin
A: 

Just because I always find this site useful, here is an online regex checker. On the right hand side it also has examples and community contributions. In there are a number of Date matching regex variations.

You can type in a load of dates you wish to match and try some of the different examples if you're not sure which is best for you. As with anything, there are multiple ways to solve the problem, but it might help you choose the one that fits best.

Ian