2013-03-20 57 views
5

我想在顶部的脚本中定义一个正则表达式常量,稍后用它来检查日期字符串的格式。如何在Perl中将正则表达式模式定义为常量?

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

$ A = “2013年3月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"; 

回答

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}$/; 
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); 
+0

'\ d'和'\ D'匹配'[0-9]'外部什么? – RickF 2013-03-20 13:59:15

+1

请参阅[perldoc perlrecharclass](http://perldoc.perl.org/perlrecharclass.html)中的“Digits”。 *这意味着除非'/ a'修饰符生效,否则'\ d'不仅与数字“0” - “9”相匹配,还与阿拉伯语,梵文和其他语言的数字相匹配。这可能会导致一些混淆和一些安全问题。* – 2013-03-20 14:52:12