如何在Perl中将正则表达式模式定义为常量?

nco*_*boy 5 regex perl datetime

我想在我的脚本顶部定义一个正则表达式常量,稍后再用它来检查日期字符串的格式.

我的日期字符串将被定义为

$ a ="2013-03-20 11:09:30.788";

但它失败了.我应该怎么做 ?

 use strict;
 use warnings;


 use constant REGEXP1 => "/^\d{4}\D\d{2}\D\d{2}\D\d{2}\D\d{2}\D\d{2}\D\d{3}$/";

 $a="2013-03-20 11:09:30.788";
 if(not $a=~&REGEXP1){
         print "not"

 }else{
         print "yes"

 }
 print "\n";
Run Code Online (Sandbox Code Playgroud)

Sin*_*nür 9

首先,让我们来看看"/^\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运算符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';
Run Code Online (Sandbox Code Playgroud)

还有一个问题:\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;
Run Code Online (Sandbox Code Playgroud)

但是,你仍然有这些价值观是否有意义的问题.如果重要,可以使用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);
Run Code Online (Sandbox Code Playgroud)


Nic*_*k P 3

您使用哪个版本的 Perl?如果你将其更改为以下内容,它在 5.8.8 中适用于我(但不适用于 5.004):

use constant REGEXP1 => qr/^\d{4}\D\d{2}\D\d{2}\D\d{2}\D\d{2}\D\d{2}\D\d{3}$/;
Run Code Online (Sandbox Code Playgroud)