0:13:46:b:4:31 # input 00:13:46:0b:04:31 # expected output #### $mac =~ s/(^|:)([\da-f])(:|$)/${1}0${2}${3}/g; #### 0:13:46:b:4:31 # input 00:13:46:0b:4:31 # produced 00:13:46:0b:04:31 # expected #### my @parts = split /:/ , $mac; foreach (@parts) { if (length == 1) { $_ = "0" . $_; } } $mac = join ":" , @parts;