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

Hello,

I have a string that looks for instance like this "Price 15.40". I want to extract the number out of that string resulting in 15.40. I have tried the following:

$string=~s/\D//g

which removes all "non-digit" characters from the string. However, then is also the decimal point "." removed which means that the result is 1540.

So my question is how to make this expression remove all "non-digit" characters EXCEPT . and ,?

Thanks!

Replies are listed 'Best First'.
Re: extracting number from string
by moritz (Cardinal) on Mar 05, 2009 at 09:33 UTC
    s/[^.\d]//g
Re: extracting number from string
by Anonymous Monk on Mar 05, 2009 at 09:35 UTC
      Thank you, but this doesn't quite do what I want. If $number = "Price 15.40", the result from

      $number=~s/^\D.//g

      is

      $number = ice 15.40

      Any idea how to get this to be just 15.40?

      Thanks!

        You copied the regex incorrectly.

        perl -e '$n = "Price 15.40"; $n =~s/[^\d.]//g; print "$n\n";'
        Produces
        15.40
        --
        seek $her, $from, $everywhere if exists $true{love};
Re: extracting number from string
by johngg (Canon) on Mar 05, 2009 at 11:45 UTC

    Alternatively, use a regular expression capture.

    $ perl -le ' $str = q{Price 15.40}; ( $str ) = $str =~ m{(\d+\.\d+)}; print $str;' 15.40 $

    I hope this is useful.

    Cheers,

    JohnGG

      For the general case, I'd replace m{(\d+\.\d+)} with m{(\d+\.?\d+)}, just in case a period is not specified in the price.