Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Regular Expression Help

by Anonymous Monk
on Jun 28, 2005 at 17:44 UTC ( [id://470732]=perlquestion: print w/replies, xml ) Need Help??

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

Hi Monks,
I have a string of numbers that comes into my program that supposable, it should have 6 digits long, like 123456, but sometimes it will come in to the program with 4 or 5 digits only, when that happens I have to add 0's to complement the string to have 6 digits.
Like if a string of number comes in with 1234, I have to add 0's to it like, 001234, so it can have 6 digits.
I have a regular expression that isn't working but my question is what is the best way to do this?
if($u=~/\d{4}?/){$u=~s/\d\d\d\d/00$u/;} if($u=~/\d{5}?/){$u=~s/\d\d\d\d\d/0$u/;}
The code above isn't working because in both cases it match the digits it finds.
Thank you!

Replies are listed 'Best First'.
Re: Regular Expression Help
by davidrw (Prior) on Jun 28, 2005 at 17:48 UTC
    Best way is with sprintf:
    $u = sprintf "%06d", $u;
    If you want to use a substitution, you could do:
    $u =~ s/(\d+)/"0"x(6-length($1)).$1/e; if length($u) < 6;
    Update: To correct your attempt:
    if($u=~/^\d{4}$/){$u=~s/\d\d\d\d/00$u/;} if($u=~/^\d{5}$/){$u=~s/\d\d\d\d\d/0$u/;} # but better written as: # $u = "00$u" if $u =~ /^\d{4}$/; # $u = "00$u" if length($u) == 4; # if you know it's digits
Re: Regular Expression Help
by Transient (Hermit) on Jun 28, 2005 at 17:46 UTC
      Hi interesting, can you give me an explaination on this code?
      Thanks!
        Sure! Basically if you take where we started : $u = ('0' x (6-length($u))).$u; we can break this up into multiple statements:
        $length_of_u = length($u); # how long is this string? $how_many_characters_short = 6-$length_of_u; # how far are we from ha +ving 6 characters? $padding = '0' x $how_many_characters_short; # this will give us as ma +ny 0's as $how_many_characters_short is long (e.g. if it is 4 - it gi +ves us '0000') $u = $padding.$u; # concatenate them together... finished!
        HTH!
Re: Regular Expression Help
by kirbyk (Friar) on Jun 28, 2005 at 17:50 UTC
    There's More Than One Way To Do It!

    I prefer: $u = sprintf("%06d", $u);

    -- Kirby, WhitePages.com

Re: Regular Expression Help
by Forsaken (Friar) on Jun 28, 2005 at 17:50 UTC
    printf is your friend. printf("%06d", $string);(untested) should do the trick.


    Remember rule one...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://470732]
Approved by davidrw
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2024-04-25 12:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found