也可以將捕獲的正則表達式模式存儲在數組中嗎?
當然是可以捕獲的子串存放在數組中:
#!/usr/bin/env perl
use strict;
use warnings;
my @patterns = map qr{$_}, qw{
(\d+)/(\d+)/(\d+)
};
my $str = '1/12/2016';
foreach my $pattern (@patterns) {
my @captured = ($str =~ $pattern)
or next;
print "'$_'\n" for @captured;
}
輸出:
'1'
'12'
'2016'
我不太明白你想用的組合做local
,eval EXPR
和eval BLOCK
在您的代碼和以下散列的目的:
my %testHash = (
'(\d+)\/(\d+)\/(\d+)' => '$1$2$3'
);
如果你試圖編纂,這種模式應該導致三個捕獲,你可以是這樣做的:
my @tests = (
{
pattern => qr{(\d+)/(\d+)/(\d+)},
ncaptures => 3,
}
);
my $str = '1/12/2016';
foreach my $test (@tests) {
my @captured = ($str =~ $test->{pattern})
or next;
unless (@captured == $test->{ncaptures}) {
# handle failure
}
}
見this answer找出如何可以自動計數數捕獲組的模式。在這個問題的答案使用技術:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
my @tests = map +{ pattern => qr{$_}, ncaptures => number_of_capturing_groups($_) }, qw(
(\d+)/(\d+)/(\d+)
);
my $str = '1/12/2016';
foreach my $test (@tests) {
my @captured = ($str =~ $test->{pattern});
ok @captured == $test->{ncaptures};
}
done_testing;
sub number_of_capturing_groups {
"" =~ /|$_[0]/;
return $#+;
}
輸出:
ok 1
1..1
您預期會發生什麼?我不明白你在做什麼。 – simbabque