I need help coming up with a regex to make sure the user enters a valid date
The string will be in the format of mm/dd/yyyy
Here is what I have come up
Regex for 0-31:
(0[1-9]|[12]\d|3[01])
Or if you don't want days with a preceding zero (e.g. 05):
([1-9]|[12]\d|3[01])
Regex for 0-31 day:
0[1-9]|[12]\d|3[01]) without prefix 0 - when "1", "23"...
([1-9]|[12]\d|3[01]) with prefix 0 - when "01", "04"
(0?[1-9]|[12]\d|3[01]) - with or without "0" - when ""
Simpler regex:
([12]\d|3[01]|0?[1-9])
Consider the accepted answer and this expression:
(0[1-9]|[12]\d|3[01])
This matches 01 but not 1
The other expression in the accepted answer:
([1-9]|[12]\d|3[01])
This matches 1 but not 01
It is not possible to add an OR clause to get them both working.
The one I suggested matches both. Hope this helps.
Is regular expression a must? If not, you better off using a different approach, such as DateTime::Format::DateManip
my @dates = (
'04/23/2009',
'01/22/2010 6pm',
'adasdas',
'1010101/12312312/1232132'
);
for my $date ( @dates )
{
my $date = DateTime::Format::DateManip->parse_datetime( $date );
die "Bad Date $date" unless (defined $date);
print "$dt\n";
}
Try it:
/(0?[1-9]|1[012])\/(0?[1-9]|[12][0-9]|3[01])\/((19|20)\d\d)/
This isn't all that hard...
qr#^
(?: 0[1-9] | 1[012] )
/
(?:
0[1-9] | 1[0-9] | 2[0-8]
| (?<! 0[2469]/ | 11/ ) 31
| (?<! 02/ ) 30
| (?<! 02/
(?= ...
(?:
.. (?: [02468][1235679] | [13579][01345789] )
| (?: [02468][1235679] | [13579][01345789] ) 00
)
)
) 29
)
/
[0-9]{4}
\z
#x