Database Reference
In-Depth Information
/^\d{4}\D\d{2}\D\d{2}$/
To permit leading zeros in values like
03
to be missing, just look for three nonempty
digit sequences:
/^\d+\D\d+\D\d+$/
Of course, that pattern is so general that it also matches other values such as US Social
Security numbers (which have the format 012-34-5678). To constrain the subpart
lengths by requiring two to four digits in the year part and one or two digits in the month
and day parts, use this pattern:
/^\d{2,4}?\D\d{1,2}\D\d{1,2}$/
For dates in other formats such as
MM-DD-YY
or
DD-MM-YY
, similar patterns apply, but
the subparts are arranged in a different order. This pattern matches both of those for‐
mats:
/^\d{2}-\d{2}-\d{2}$/
To check the values of individual date parts, use parentheses in the pattern and extract
the substrings after a successful match. If you expect dates to be in ISO format, for
example, do this:
if
(
$val
=~
/^(\d{2,4})\D(\d{1,2})\D(\d{1,2})$/
)
{
(
$year
,
$month
,
$day
)
=
(
$1
,
$2
,
$3
);
}
The library file
lib/Cookbook_Utils.pm
in the
recipes
distribution contains several of
these pattern tests, packaged as function calls. If the date doesn't match the pattern, they
return
undef
. Otherwise, they return a reference to an array containing the broken-out
values for the year, month, and day. This can be useful for performing further checking
on the components of the date. For example,
is_iso_date()
looks for dates that match
ISO format. It's defined as follows:
sub
is_iso_date
{
my
$s
=
$_
[
0
];
return
undef
unless
$s
=~
/^(\d{2,4})\D(\d{1,2})\D(\d{1,2})$/
;
return
[
$1
,
$2
,
$3
];
# return year, month, day
}
Use the function like this:
my
$ref
=
is_iso_date
(
$val
);
if
(
defined
(
$ref
))
{
# $val matched ISO format pattern;
# check its subparts using $ref->[0] through $ref->[2]
}
else