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 this case.
Use str.strip(chars) on a string with "0" as chars to remove zeros from the beginning and end of the string.
Approach: We use the StringBuffer class as Strings are immutable. Count leading zeros by iterating string using charAt(i) and checking for 0 at the “i” th indices. Use StringBuffer replace function to remove characters equal to the above count using replace() method.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With