gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:39:21 25 4
gpt4 key购买 nike

我想在我的脚本顶部定义一个 regexp 常量,稍后使用它来检查日期字符串的格式。

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

$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";

最佳答案

首先我们来看"/^\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.…

If you print the value of REGEXP1, you will get /^d{4}Dd{2}Dd{2}Dd{2}Dd{2}Dd{2}Dd{3} (*wait, what happened to $/?). Clearly, that does not look like the pattern you wanted.

Now, you could type "/^\\d{4}\\D\\d{2}\\D\\d{2}\\D\\d{2}\\D\\d{2}\\D\\d{2}\\D\\d{3}\$/" and then interpolate that string into a pattern, but that's too much work. Instead, you can define your constant using the 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);

关于regex - 如何在 Perl 中将正则表达式模式定义为常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15514108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com