首先,让我们来看看"/^\d{4}\D\d{2}\D\d{2}\D\d{2}\D\d{2}\D\d{2}\D\d{3}$/";
如果您对警告,你应该得到:
Unrecognized escape \d passed through at C:\temp\jj.pl line 7.
Unrecognized escape \D passed through at C:\temp\jj.pl line 7.
Unrecognized escape \d passed through at C:\temp\jj.pl line 7.
…
如果您打印的值为REGEXP1
,您将获得/^d{4}Dd{2}Dd{2}Dd{2}Dd{2}Dd{2}Dd{3}
(*等待,发生了什么事$/
?)。显然,这看起来不像你想要的模式。
现在,您可以键入"/^\\d{4}\\D\\d{2}\\D\\d{2}\\D\\d{2}\\D\\d{2}\\D\\d{2}\\D\\d{3}\$/"
,然后将该字符串内插到一个模式中,但这太多了。相反,你可以使用regexp quote operator, qr
定义常量:
#!/usr/bin/env perl
use 5.012;
use strict;
use warnings;
use constant REGEXP1 => qr/^\d{4}\D\d{2}\D\d{2}\D\d{2}\D\d{2}\D\d{2}\D\d{3}$/;
my $s = "2013-03-20 11:09:30.788";
say $s =~ REGEXP1 ? 'yes' : 'no';
还有一个疑难杂症:\d
和\D
将分别匹配不仅仅是[0-9]
和[^0-9]
更多。所以,你可以写下你的模式:
use constant REGEXP1 => qr{
\A
(?<year> [0-9]{4}) -
(?<month> [0-9]{2}) -
(?<day> [0-9]{2}) [ ]
(?<hour> [0-9]{2}) :
(?<min> [0-9]{2}) :
(?<sec> [0-9]{2}) [.]
(?<msec> [0-9]{3})
\z
}x;
但是,你仍然留下这些值是否有意义的问题。如果有问题,您可以使用DateTime::Format::Strptime。
#!/usr/bin/env perl
use 5.012;
use strict;
use warnings;
use DateTime::Format::Strptime;
my $s = "2013-03-20 11:09:30.788";
my $strp = DateTime::Format::Strptime->new(
pattern => '%Y-%m-%d %H:%M:%S.%3N',
on_error => 'croak',
);
my $dt = $strp->parse_datetime($s);
say $strp->format_datetime($dt);
'\ d'和'\ D'匹配'[0-9]'外部什么? – RickF 2013-03-20 13:59:15
请参阅[perldoc perlrecharclass](http://perldoc.perl.org/perlrecharclass.html)中的“Digits”。 *这意味着除非'/ a'修饰符生效,否则'\ d'不仅与数字“0” - “9”相匹配,还与阿拉伯语,梵文和其他语言的数字相匹配。这可能会导致一些混淆和一些安全问题。* – 2013-03-20 14:52:12