开发者

Remove leading zeroes but not all zeroes

开发者 https://www.devze.com 2023-02-25 15:27 出处:网络
How can I remove all the leading zeroes but leave a final zero if the value only contains zeroes? for example:

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

for example:

my $number = "0000";

I would like to have:

my $number = "0";

I tried:

$number =~ s/^0*//; 

but this of course removes all the zeroes in thi开发者_JS百科s case.


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.


This doesn't need to be done as a regex.

my @nums = qw/ 00000 000 000001 002 00000005 00000064 /;
@nums = map { $_ + 0 } @nums;


$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;


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.


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


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

my $var = '0000035600000';
$var += 0;


You could also use the sprintf function in Perl:

# Input variables
$valuesA = "0";
$valuesB = "00001";
$valuesC = "000.1";
$valuesD = "00010";

# Format number with zero leading zeroes
# $valuesA = sprintf("%0d", $valuesA);
$valuesA = sprintf("%0g", $valuesA);
$valuesB = sprintf("%0g", $valuesB);
$valuesC = sprintf("%0g", $valuesC);
$valuesD = sprintf("%0g", $valuesD);

# Output variables
print "valuesA: $valuesA\n"; # returns "0"
print "valuesB: $valuesB\n"; # returns "1"
print "valuesC: $valuesC\n"; # returns "0.1"
print "valuesD: $valuesD\n"; # returns "10"


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号