CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
How to isolate numbers from a string

 



mk_bold
Novice

Mar 11, 2014, 4:11 PM

Post #1 of 3 (1623 views)
How to isolate numbers from a string Can't Post

if I have a string $line = llalallala 3.5$ blabla.
How do I isolate the 3.5?

My method so far would be to remove all non digits
"$line =~ s/^\D+//g;" but that do also remove the . how do I keep that?


BillKSmith
Veteran

Mar 12, 2014, 6:17 AM

Post #2 of 3 (1618 views)
Re: [mk_bold] How to isolate numbers from a string [In reply to] Can't Post

That is not a good way to do the job in perl.
A digit (or a period as in you example)
elsewhere in the string could change your answer.
You should use a regular expression to match the format
you expect your number to have.

The following will correctly match most decimal
numbers. If there is more than one in the string,
this returns the first of them.


Code
$line = 'llalallala 3.5$ blabla.'; 
($number) = $line =~m/([-+]?\d+\.\d+)/;


An even beter way would be to use the module Regexp::Common.
It correcty handles special cases which you may not even think of.
It may be overkill for your application,
but is good to know that it is available.
Good Luck,
Bill


mk_bold
Novice

Mar 12, 2014, 6:27 AM

Post #3 of 3 (1616 views)
Re: [BillKSmith] How to isolate numbers from a string [In reply to] Can't Post

Thank you, I see that I should probably take a harder look at the reg. expression, because I did not think about that kind of solution, but it seems fairly logical.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives