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

I'm fairly new too Perl, so bear with me if this is a dumb question. I have a string and I want to know how many numbers are in it. How would I go about this in Perl? For example:
$foo = "spider9832man23";
I want to be able to count and see that there are 6 numbers in $foo. Any ideas?

Replies are listed 'Best First'.
Re: number of numbers in a string
by gaal (Parson) on Aug 12, 2004 at 17:58 UTC
    (Count *numerals*, you mean. You have two numbers there, or possibly many more if you allow for substrings.)

    $foo = "spider9832man23"; print "count = " . $foo =~ y/0-9//;
      Hmm... this could be an interesting question if we where try to count the numbers ... you know 9832 is a number 832 is too and so is 32 and 2 and 983. What'cha think?

      Plankton: 1% Evil, 99% Hot Gas.
        Accounting only for integers, we have:
        my $n = 0; $n += map .5*(1+length)*length, $s =~ /\d+/g;
        This makes use of the triangular pattern that the number "1234" has 10 "embedded numbers" (1234, 123, 12, 1, 234, 23, 2, 34, 3, 4). No need to put all that hard work in the regex itself. Although, if you wanted to, it'd be:
        our $n; $s =~ /\d+(??{ ++$n })(?!)/;
        _____________________________________________________
        Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
        How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
Re: number of numbers in a string
by johnnywang (Priest) on Aug 12, 2004 at 18:08 UTC
    The following should do:
    $foo = "spider9832man23"; my @digits = ($foo =~ /\d/g); print scalar(@digits); # print 6
    Looking at merlyn's Forcing list context, the above can be simplified as:
    $foo = "spider9832man23"; print ( $count = () = $foo =~ /\d/g); # prints: 6
      # or: ++$count while $foo =~ /\d/g; # or: $count = $foo =~ s/(\d)/$1/g; # or: $count = () = $foo =~ /\d/g; # or: $foo =~ s/(\d)/++$count; $1/ge; # etc.
      But y/// (aka tr///) is the perfect-fit tool for this job.

      Update: s/gee/ge/; thanks, japhy; yes, a typo

        You have an extra /e modifier on your last regex, but it ends up being harmless. But it's still extraneous; while it might be a typo, it might also be a sign of a misunderstanding of its purpose.
        _____________________________________________________
        Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
        How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart