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

时间:2013-03-20 02:18:46

标签: 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";

2 个答案:

答案 0 :(得分: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 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);

答案 1 :(得分: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}$/;