Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove leading zeroes but not all zeroes

Tags:

regex

perl

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.

like image 919
perlfoo Avatar asked Apr 15 '11 14:04

perlfoo


People also ask

How do I remove zeros in front of a number in Python?

Use str.strip(chars) on a string with "0" as chars to remove zeros from the beginning and end of the string.

How do you remove preceding zeros in Java?

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.


2 Answers

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.

like image 141
Mat Avatar answered Sep 19 '22 16:09

Mat


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

my @nums = qw/ 00000 000 000001 002 00000005 00000064 /;
@nums = map { $_ + 0 } @nums;
like image 42
Oesor Avatar answered Sep 19 '22 16:09

Oesor