Skip to content

Instantly share code, notes, and snippets.

@dallaylaen
Forked from Ovid/date.pl
Last active August 27, 2019 17:05
Show Gist options
  • Save dallaylaen/9dffb01f6167c81ae7baee8eed246b18 to your computer and use it in GitHub Desktop.
Save dallaylaen/9dffb01f6167c81ae7baee8eed246b18 to your computer and use it in GitHub Desktop.
Partial desription of a date matching regex yyyy-mm-dd
#!/usr/bin/env perl
use strict;
use warnings;
use Test::Most;
my %days = (
28 => qr/0[1-9]|1[0-9]|2[0-8]/,
29 => qr/0[1-9]|[12][0-9]/,
30 => qr/0[1-9]|[12][0-9]|30/,
31 => qr/0[1-9]|[12][0-9]|3[01]/,
);
my %month = (
'01' => 31,
'02' => 28,
'03' => 31,
'04' => 30,
'05' => 31,
'06' => 30,
'07' => 31,
'08' => 31,
'09' => 30,
'10' => 31,
'11' => 30,
'12' => 31,
);
my $normal_year = join '|', map {
qr($_-$days{ $month{$_} })
} sort keys %month;
$normal_year = qr/\d{4}-$normal_year/;
my $leap_year_4 = qr/\d{2}(?:0[48]|[2468][048]|[13579][26])/;
my $leap_year_400 = qr/(?:[02468][048]|[13579][26])00/;
my $leap_year = qr($leap_year_4|$leap_year_400);
my $yyyy_mm_dd = qr($normal_year|$leap_year-02-29);
my %examples_for = (
pass => [
'1999-12-31',
'1999-12-30',
'1999-12-01',
'1999-01-31',
'2000-02-29',
'1904-02-29',
],
fail => [
'1999-02-31',
'1999-2-31',
'1999-20-12',
'1999-12-00',
'99-01-31',
'1999-00-31',
'1900-02-29',
'2019-02-29',
]
);
foreach my $date ( $examples_for{pass}->@* ) {
ok $date =~ $yyyy_mm_dd, "$date should be a valid date";
}
foreach my $date ( $examples_for{fail}->@* ) {
ok $date !~ $yyyy_mm_dd, "$date should not be a valid date";
}
done_testing;
note $yyyy_mm_dd;
@dallaylaen
Copy link
Author

The resulting rex is (?^:(?^:\d{4}-(?^:01-(?^:0[1-9]|[12][0-9]|3[01]))|(?^:02-(?^:0[1-9]|1[0-9]|2[0-8]))|(?^:03-(?^:0[1-9]|[12][0-9]|3[01]))|(?^:04-(?^:0[1-9]|[12][0-9]|30))|(?^:05-(?^:0[1-9]|[12][0-9]|3[01]))|(?^:06-(?^:0[1-9]|[12][0-9]|30))|(?^:07-(?^:0[1-9]|[12][0-9]|3[01]))|(?^:08-(?^:0[1-9]|[12][0-9]|3[01]))|(?^:09-(?^:0[1-9]|[12][0-9]|30))|(?^:10-(?^:0[1-9]|[12][0-9]|3[01]))|(?^:11-(?^:0[1-9]|[12][0-9]|30))|(?^:12-(?^:0[1-9]|[12][0-9]|3[01])))|(?^:(?^:\d{2}(?:0[48]|[2468][048]|[13579][26]))|(?^:(?:[02468][048]|[13579][26])00))-02-29)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment