删除前导零但不是所有零 [英] Remove leading zeroes but not all zeroes
本文介绍了删除前导零但不是所有零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果值只包含零,如何删除所有前导零但保留最后一个零?
How can I remove all the leading zeroes but leave a final zero if the value only contains zeroes?
例如:
my $number = "0000";
我想要:
my $number = "0";
我试过了:
$number =~ s/^0*//;
但这当然会在这种情况下删除所有零.
but this of course removes all the zeroes in this case.
推荐答案
这应该有效:
$number =~ s/^0*(\d+)$/$1/;
0 -> 0
0000 -> 0
0001 -> 1
事实证明这有点太复杂了.这也应该有效:
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.
请查看 Oesor 的答案:它也很可爱,不涉及正则表达式.
Do check out the answer from Oesor: it's pretty sweet too, no regex involved.
这篇关于删除前导零但不是所有零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文