perl -wMstrict -le "my @strs = ( '1,2,3,4', '8,9,10,11', '7,8,9,10', '12,13,14,15', '1,23,456', '123,45,6', ); ;; my $not_after_digit = qr{ (? }, $s; $s =~ s{ $not_after_digit $before_solitary_digit }{0}xmsg; print qq{'$s'}; } " '1,2,3,4' -> '01,02,03,04' '8,9,10,11' -> '08,09,10,11' '7,8,9,10' -> '07,08,09,10' '12,13,14,15' -> '12,13,14,15' '1,23,456' -> '01,23,456' '123,45,6' -> '123,45,06'