Ear*_*ome 0 regex perl capture-group
有没有办法在多个绑定表达式中使用捕获组并捕获所有组?
#!/usr/bin/perl
use strict;
use warnings;
countDays(1,"2015-3-21","2016-3-24");
sub countDays {
die "Check formatting"
unless ($_[0] =~ m/([1-7])/ &&
$_[1] =~ m/^(\d{4})-(\d{1,2})-(\d{1,2})$/ &&
$_[2] =~ m/^(\d{4})-(\d{1,2})-(\d{1,2})$/);
# testing
print "$1\n$2\n$3\n$4\n$5\n$6\n$6\n";
}
Run Code Online (Sandbox Code Playgroud)
这只是抓住了最后三组:$1,$2,和$3.
编辑Avinash Raj建议的预期输出:
1
2015
3
21
2016
3
24
Run Code Online (Sandbox Code Playgroud)
不,每次成功匹配都会重置所有捕获变量.但你可以这样做:
sub countDays {
my @match1 = $_[0] =~ m/([1-7])/
and
my @match2 = $_[1] =~ m/^(\d{4})-(\d{1,2})-(\d{1,2})$/
and
my @match3 = $_[2] =~ m/^(\d{4})-(\d{1,2})-(\d{1,2})$/
or die "Check formatting";
print "@match1\n@match2\n@match3\n";
}
Run Code Online (Sandbox Code Playgroud)