如何在 Perl 中处理以下模式匹配

How to handle below pattern matching in Perl

如何进行下面提到的模式匹配?

下面的输入在数组中:

@array=("gs : asti:34:234", "gs : asti:344:543:wet");

我使用了 foreach loop 以便将它们拆分并将它们推入一个数组。

帮我解决以下问题。

foreach(@array)
{
    if($_ =~ /gs/ig)
    {

        my @arr2 = split(":",$_); #Splitting the matched pattern
        push(@y,$arr2[1]);
    }
}

实际输出为:asti , asti
Desired/Expected 输出:asti:34:234 , asti:344:543:wet

你可以这样做,split字符串只有两部分:

use strict;
use warnings;

my @array=('gs : asti:34:234', 'gs : asti:344:543:wet');

foreach(@array)
{
    if($_ =~ m/gs/ig)
    {
        my @arr2 = split(":", $_, 2);
        $arr2[1] =~ s/^\s+//;   #to remove the white-space
        push(my @y,$arr2[1]);
        print "@y\n";
    }
}

输出:

asti:34:234
asti:344:543:wet

使用正则表达式捕获而不是拆分可以简化代码,反正你已经在使用正则表达式了,为什么不省一步:

my @array = ("gs : asti:34:234", "gs : asti:344:543:wet");
my @y     = ();
foreach my $e (@array) {
    push @y,  if $e =~ m/^gs : (.*)$/i;
}