Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

what is the best way to seperate the digits and strings from variable ?

by swaroop (Beadle)
on May 09, 2005 at 10:35 UTC ( [id://455137]=perlquestion: print w/replies, xml ) Need Help??

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

Hi all,

what is the best way to seperate the digits and strings from variable ?

example:
$variable = 12345(checkthis);
I would like to seperate the digits and strings and I need only digits 12345.

thanks,
swaroop

Replies are listed 'Best First'.
Re: what is the best way to seperate the digits and strings from variable ?
by tlm (Prior) on May 09, 2005 at 10:49 UTC

    For this simple case,

    $digits = $1 if $variable =~ /(\d+)/;
    will do the job, but things rarely stay this simple :-).

    the lowliest monk

Re: what is the best way to seperate the digits and strings from variable ?
by polettix (Vicar) on May 09, 2005 at 10:46 UTC
    Hi swaroop, please post these questions in Seekers of Perl Wisdom instead of Perl Monks Discussion. Also, try to work your examples out a little better: use code tags and quotes around strings :)

    Your question is a little vague, but if you want to extract digits at the beginning of a string you can use the following regex:

    my $variable = '12345(checkthis)'; $variable =~ /^(\d*)/; my $start_digits = $1;
    or, more concisely:
    my $variable = '12345(checkthis)'; my ($start_digits) = $variable =~ /^(\d*)/;
    Note that in the last example you HAVE to put parenthesys around $start_digits, to force a list/array context evaluation.

    Flavio (perl -e 'print(scalar(reverse("\nti.xittelop\@oivalf")))')

    Don't fool yourself.

      Please, test your code.

      \d* will match 0 (ZERO) or more digits.

      Thus, it will happily match an empty string at the beginning of a string like "abc123" and return a 0 length string. Try it.

      The right expression to use in this case is \d+.

      Moreover, a capturing regular expression should always be used with a test:

      my $num; my $variable = "abc123"; if ( $variable =~ /(\d+)/) { $num = $1; }
        Please read the OP and the variable names in the test code before slapping hands. You can be right from your implied point of view, but I had my rationale when posting (which implies that I tested my code, of course)

        Here, I'm considering digits as a character class, not as components of a number whose semantic is different from that of a string; this is why I name my variable $start_digits, not $num as you do. As you've surely noted, the OP never talks about numbers, always about digits (anyway, as I noted in my post, the OP was not clear about the usage of this extracted data).

        Thus, when I thought about putting "*" or "+"*, I considered that if there were no digits it was good, and the returned string would be empty.

        I think you can agree with me that, had the OP asked for initial letters, the regex:

        my $variable = "abc123"; my ($letters) = $variable =~ /^([a-zA-Z]*)/;
        would do the job.

        *I swear I thought about that!

        Flavio (perl -e 'print(scalar(reverse("\nti.xittelop\@oivalf")))')

        Don't fool yourself.
          A reply falls below the community's threshold of quality. You may see it by logging in.
        Please, test your code.

        Testing code in replies is encouraged (if that), but not required. One must simply have the common sense to accept that occasionally untested code will prove itself wrong, and one must be willing to correct it should that occur.

Re: what is the best way to seperate the digits and strings from variable ?
by gopalr (Priest) on May 09, 2005 at 11:23 UTC
    $variable = '12345(checkthis)'; $digit=$1 if $variable=~m#([0-9]+)#; print $digit;

    Output:

    12345
Re: what is the best way to seperate the digits and strings from variable ?
by sh1tn (Priest) on May 09, 2005 at 11:35 UTC
    my $var = '12345text6789'; my $digits = ''; $digits .= $1 while $var =~ /([0-9]+)/g; if( $digits ){ print "digits are $digits\n" }else{ print "no digits detected\n" }


Re: what is the best way to seperate the digits and strings from variable ?
by thcsoft (Monk) on May 09, 2005 at 13:29 UTC
    er... what'a all this for? a tupper-party?

    just assume we'll going to try to extract every digits from any kind of source:
    open SOURCE, "somefile" || die $!; my @source = <SOURCE>; close SOURCE; my $digits = ''; map { my $in = $_; $in =~ s/\D//g; $digits .= $in; } @source;
    i mean, apart from that the task itself is rather questionable, i found it questionably funny thinking about it for some time. :D

    never mind, im kidding.

    language is a virus from outer space.
Re: what is the best way to seperate the digits and strings from variable ?
by radiantmatrix (Parson) on May 09, 2005 at 17:47 UTC

    Hm, your exact request is vague. To extract a list of digits from a data stream, I suggest one of the following:

    my $variable = '12345(checkthis)'; my @digits; undef @digits; while ($variable =~ /\d/g) { push @digits, $& }
    my $variable = '12345(checkthis)'; my @digits; undef @digits; foreach (split '', $variable) { push @digits, $_ if /\d/ }
    Each case will result in a list of digits stored in @digits

    The Eightfold Path: 'use warnings;', 'use strict;', 'use diagnostics;', perltidy, CGI or CGI::Simple, try the CPAN first, big modules and small scripts, test first.

Re: what is the best way to seperate the digits and strings from variable ?
by cog (Parson) on May 09, 2005 at 15:31 UTC
    Actually, I think it's worth mentioning that if you want only the digits in the beginning of the string you can do something like this:

    $variable = '12345(checkthis)'; $variable += 0;

    That numifies $variable, which happens to exclude everything starting from the first non-digit character.

    Other (twisted) ways of doing the same would include the spacestation:

    $variable = -+- '12345(checkthis)';

    If, OTOH, you really want all the digits, regardless of them being in the beginning of the string, or even of them being together or separated by other chars, you can always use some silly regexen twisting such as:

    $variable = join '', "12345(checkthis)" =~ /\d*/g;

      That last is probably better written as
      ($variable = '12345(checkthis)') =~ tr/0-9//dc;

      Caution: Contents may have been coded under pressure.
        I said "silly regexen twisting". I was meaning to show that there are a bunch of ways to do it (slightly off-topic, I know, but still worth mentioning).

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (3)
As of 2024-03-19 05:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found