Regular expression – hold the first two parts of the string have separator

Is there a more concise/perfect way of the following:

my @components = split /-/, $original ;
my $final_string = $components[0]."-".$components[1];

The input is a maximum of 2 strings-the last one is optional. I always I want to keep the first part. That is, 10-9-1 should become 10-9 and 10-9, because the input should remain 10-9

use Modern::Perl;

my $re = qr/-\d+\K.*$/;
while(< DATA>) {
chomp;
s/$re//;
say;
}
__DATA__
10-9-1
10-9

Only one string:

my $original = '10-9-1';
(my $final = $original) =~ s/-\d+\K.*$//;
say $final;

Explantion:

 s/
-# find the first dash in the string
\d+ # 1 or more digits
\K # forget all we have seen until this posiiton
.* # rest of the line
$ # end of line
//

Is there a more concise/perfect way of the following:

my @components = split /-/, $original;
my $final_string = $components[0]."-".$components[1];

The input is a string of up to 2 – the last one is optional. I always want to keep the first part. That is 10- 9-1 should become 10-9 and 10-9, because the input should remain 10-9

use Modern::Perl;

my $re = qr/-\d+\K.*$/;
while() {
chomp;
s/$re//;
say;
}
__DATA__
10-9-1
10-9

Only one string:

< p>

my $original = '10-9-1';
(my $final = $original) =~ s/-\d+\K.*$//;
say $final;

Explantion:

s/
-# find the first dash in the string
\d+ # 1 or more digits
\K # forget all we have seen until this posiiton
.* # rest of the line
$ # end of line
//

Leave a Comment

Your email address will not be published.