Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

extracting number from string

by samuelalfred (Sexton)
on Mar 05, 2009 at 09:31 UTC ( [id://748471]=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (1)
As of 2024-04-25 04:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found