模式匹配如何使用perl

时间:2015-03-17 05:20:21

标签: regex perl

我有变量a:b:c a:b:d c:d:e,我需要将输出显示为a-b a-b c-d

我尝试以下代码

$res="A:B:C A:B:D C:D:E";

$res=~s/\:/\-/g;

$res=~s/..$//mgs;
print "$res\n";

但我没有收到输出

4 个答案:

答案 0 :(得分:3)

use strict;
use warnings;
$res = "A:B:C A:B:D C:D:E";
$res =~ s{([a-z]):([a-z]):[a-z]}{$1-$2}ig;

答案 1 :(得分:0)

这就像你问的那样

use strict;
use warnings;

my $res = "\nA:B:C \nA:B:D \nC:D:E";

my @fields = map { join '-', (split /:/)[0,1] } split ' ', $res;
$res = "@fields\n";

print $res, "\n";

<强>输出

A-B A-B C-D

答案 2 :(得分:0)

或者您也可以使用regex match

#!/usr/bin/perl -w
use strict;

my $res="A:B:C A:B:D C:D:E";
my @arr = split(/ /,$res);
my $new = "";
for(@arr) {
    /^([a-zA-Z]):([A-Za-z])/;
    $new .= $1."-".$2." ";
}
chop $new;
print $new;

<强>输出

A-B A-B C-D

答案 3 :(得分:0)

$res = "A:B:C A:B:D C:D:E";
$res =~ s/(\w):(\w):\w/$1-$2/g;

# $res <-- A-B A-B C-D