Karger78 has asked for the wisdom of the Perl Monks concerning the following question:

Hello all, I am trying to remove leading zeros froma hex number. I have been banging my head off the wall on this one. Anyone have a quick regex to remove leading zeros from a hex number?
  • Comment on RegEx to remove leading zeros from a hex number

Replies are listed 'Best First'.
Re: RegEx to remove leading zeros from a hex number
by toolic (Bishop) on May 16, 2011 at 20:51 UTC
    One way is to use sprintf and hex:
    use warnings; use strict; for (qw(00ab 005 5 000 0)) { my $nz = sprintf '%x', hex; print "$_ ---> $nz\n"; } __END__ 00ab ---> ab 005 ---> 5 5 ---> 5 000 ---> 0 0 ---> 0
Re: RegEx to remove leading zeros from a hex number
by ikegami (Patriarch) on May 16, 2011 at 20:54 UTC
Re: RegEx to remove leading zeros from a hex number
by JavaFan (Canon) on May 16, 2011 at 20:35 UTC
    $var =~ s/^0+//g;

    It even works on other strings not containing hex numbers!

      ... and gets rid of all zeros. D'oh!
      use warnings; use strict; my $var = '0000'; $var =~ s/^0+//g; print ">>>$var<<<\n"; __END__ >>><<<
        Well, yes. Removing the leading zeros from a string containing only zeros leaves zero zeros. What you do you think should happen? Leaving a string with leading zeros, or a string containing non-zeros? Neither seems to be correct.
Re: RegEx to remove leading zeros from a hex number
by John M. Dlugosz (Monsignor) on May 17, 2011 at 10:19 UTC
    I just did that in a text editor. I replaced s/0x0/0x/ and re-ran until it reported zero replacements.
Re: RegEx to remove leading zeros from a hex number
by Anonymous Monk on May 19, 2016 at 11:16 UTC
    s/^0+(.+)//s This one even capture if the input is 000 o/p-0