perl - 在while内填充regex组中的几个变量

时间:2013-07-26 13:48:27

标签: regex perl

我正在学习perl,现在我正在尝试同时填充几个变量,从匹配捕获中,在一个while组中。我有“长”版本,如下:

$pc = ...
while ($pc =~ m/bla1(.*?)bla2(.*?)bla3(.*?)bla4(.*?)bla5(.*?)bla6(.*?)bla7/g) {
    $var1 = $1; 
    $var2 = $2;
    $var3 = $3;
    $var4 = $4;
    $var5 = $5;
    $var6 = $6;
    ...
}

单次捕获(在while循环之外)我知道我可以这样做:

my $string = 'abcde';
my @captures = $string =~ m/.(.)(.)(.)./;
my ($aa,$ab,$ac) = @captures;
print ("$aa - $ab - $ac\n");

有没有办法立即填充while循环中的所有变量?我是否需要执行类似下面的代码,或者是否更容易(不需要2个正则表达式)方式?

while ($pc =~ m/bla1(.*?)bla7/g) {
    my @captures = $1 =~ m/(.*?)bla2(.*?)bla3(.*?)bla4(.*?)bla5(.*?)bla6(.*?)/;
    ($var1,$var2,$var3,$var4,$var5,$var6) = @captures;
    ...
}

提前致谢。

2 个答案:

答案 0 :(得分:6)

好吧,你可以用

while ($pc =~ m/bla1(.*?)bla2(.*?)bla3(.*?)bla4(.*?)bla5(.*?)bla6(.*?)bla7/g) {
    my ($var1, $var2, $var3, $var4, $var5, $var6) = ($1, $2, $3, $4, $5, $6);
    ... $var3 ...
}

while ($pc =~ m/bla1(.*?)bla2(.*?)bla3(.*?)bla4(.*?)bla5(.*?)bla6(.*?)bla7/g) {
    my @vars = ($1, $2, $3, $4, $5, $6);
    ... $vars[2] ...
}

sub captures { map substr($_[0], $-[$_], $+[$_] - $-[$_]), 1..$#- }

while ($pc =~ m/bla1(.*?)bla2(.*?)bla3(.*?)bla4(.*?)bla5(.*?)bla6(.*?)bla7/g) {
    my @vars = captures($pc);
    ... $vars[2] ...
}

sub captures { no strict 'refs'; map $$_, 1..$#- }

while ($pc =~ m/bla1(.*?)bla2(.*?)bla3(.*?)bla4(.*?)bla5(.*?)bla6(.*?)bla7/g) {
    my @vars = captures();
    ... $vars[2] ...
}

while ($pc =~ m/bla1(?<var1>.*?)bla2(?<var2>.*?)bla3(?<var3>.*?)bla4(?<var4>.*?)bla5(?<var5>.*?)bla6(?<var6>.*?)bla7/g) {
    ... $+{vars3} ...
}

答案 1 :(得分:0)

尝试:

$pc = ...
while ( my @captured = $pc =~ m/bla1(.*?)bla2(.*?)bla3(.*?)bla4(.*?)bla5(.*?)bla6(.*?)bla7/g) {