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

Hello, How would I extract a number from a string? For example:
"string 23 string" returns 23
"05 stringstring" returns 5
"sljkdf ls st 3" returns 3
"sldk27lskdf23lksj923" returns 27

TIA,
blax

Replies are listed 'Best First'.
Re: Extracting a number from a string
by Abigail-II (Bishop) on Jan 12, 2003 at 17:14 UTC
    use Regexp::Common; /$RE{number}{int}/;

    Abigail

      I dont think you need a module to make that, any way 01 or 1 is still a number and zero is a neutral number.
      #!/usr/bin/perl -w $_="Testing numbers 12"; print "Numbers: <$1>" if ( /(\d*)/ );
      I think this might work
        But it doesn't work, that's exactly the reason why you should use a module!

        Zaxo has a 'working' hand-rolled solution somewhere else in this thread, though it breaks on negative numbers (which might or might not be OK, depending on the input data).

        Granted, in this simple case it might be OK not to use a module but still you have to know what you are doing. In all but the most trivial cases, use the module and spare yourself the extra debugging work. Try e.g. to match a general floating point number like -2.4345e-12 and then you know why it's better/easier/quicker to use a module.

        -- Hofmator

Re: Extracting a number from a string
by Zaxo (Archbishop) on Jan 12, 2003 at 16:52 UTC
    my ($num) = $string =~ /(\d+)/; # Added $num += 0;

    $num is in parens to put the right side into list context, which makes match return the value matched.

    After Compline,
    Zaxo

      That would make "05 stringstring" return 05, though, not 5.

      Maybe something like:

      my ($num) = $string =~ /0*(\d+)/;

      That would also correctly set $num to 0 for a string like "string0string", right?


      Queue
      still making his way through Mastering Regular Expressions