Remove leading zeroes but not all zeroes

后端 未结 7 1507
借酒劲吻你
借酒劲吻你 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:31

    Just add 0 to the string so that it's implicitly converted to a number:

    my $var = '0000035600000';
    $var += 0;
    
    0 讨论(0)
  • 2020-12-18 21:36

    This should work:

    $number =~ s/^0*(\d+)$/$1/;
    
    0    -> 0
    0000 -> 0
    0001 -> 1
    

    Edit: turns out that's just a bit too complicated. This should also work:

    $number =~ s/0*(\d+)/$1/;
    

    but I'm not sure which is better, depends on the use case.

    Do check out the answer from Oesor: it's pretty sweet too, no regex involved.

    0 讨论(0)
  • 2020-12-18 21:39

    If your $number is an integer, another way is to use printf:

    for my $number (qw(005 05 5 000 0 500)) {
        printf "%d\n", $number;
    }
    
    __END__
    
    5
    5
    5
    0
    0
    500
    

    Edit: As ysth points out, it works for all integers, not just positive integers as I originally stated.

    0 讨论(0)
  • 2020-12-18 21:42

    Well if you want to replace all by one just change to s/^0+/0/ ?

    However, this will replace all leading 0's by one 0 so if you have leading zeros before numbers you will need Mats construct.

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-12-18 21:46

    Some answers are implicitly assuming there are only digits present or that $number is in fact a number. If this is not the case:

    s/^0+(?=.)//s
    

    Or even:

    substr($number,0,-1) =~ s/^0+//s
    
    0 讨论(0)
提交回复
热议问题