Perl在000000000000中添加冒号

时间:2015-11-04 09:46:45

标签: perl

我的代码:

#!/usr/bin/perl

$macaddress = "000000000000";

print "$macaddress\n"; # Now how to make it 00:00:00:00:00:00

如何制作00:00:00:00:00:00?

enter image description here

3 个答案:

答案 0 :(得分:3)

这样做:

print join ( ":", $macaddress =~ m/(\d{2})/g );

我们在“两位数”上使用正则表达式匹配。我们重复它,所以匹配返回一个元素列表,每个元素都是两位数。然后在join:

但是,如果您正在处理十六进制数字,那将无效 - 您还需要处理字母:

my $macaddress = "c0ffeedeAD02";
print join ( ":", lc($macaddress) =~ m/([0-9a-f]{2})/gi );

将打印:

c0:ff:ee:de:ad:02 

lc小写一切)。

注意 - 此技术匹配任何配对数字,并忽略其他任何内容。所以你可以很高兴地做到:

$macaddress = "c0-ff-ee-de-AD-02";
$macaddress = "c0:ff:ee:de:AD:02";
$macaddress = "c0XffJee*de&AD!02";

它正在加入指定的分隔符。你可以使用另一个(或没有):

$macaddress = "c0XffJee*de&AD!02";
print join ( "", lc($macaddress) =~ m/([0-9a-f]{2})/gi );
#still prints: c0ffeedead02

答案 1 :(得分:1)

另一个选择是替换它来做

my $macaddress = "000000000000"; 
$macaddress =~ s/(?<=\d{2})(\d{2})/:$1/g;
print $macaddress;

如果要分隔任意两个字符,请使用此

~s/(?<=..)(..)/:$1/g;

谢谢@glenn jackman:)

答案 2 :(得分:0)

您还可以使用substr

for (my $pos = 2; $pos < length $macaddress; $pos += 3) {
    substr $macaddress, $pos, 0, ':';
}