Remove leading zeroes but not all zeroes

后端 未结 7 1511
借酒劲吻你
借酒劲吻你 2020-12-18 21:13

How can I remove all the leading zeroes but leave a final zero if the value only contains zeroes?

for example:

my $number = \"0000\";
7条回答
  •  轮回少年
    2020-12-18 21:43

    $number =~ s/^0+(?=\d)//;
    

    The positive lookahead ensures there's at least one digit left, and using + instead of * means the substitution is skipped if there are no leading zeroes.

    If you're trying to normalize groups of numbers in a single string, just use \b instead of ^, and do a global substitution:

    my $data = "0225 0000 030";
    $data =~ s/\b0+(?=\d)//g;
    

提交回复
热议问题