Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Extract numbers

by tye (Sage)
on Mar 01, 2001 at 04:23 UTC ( [id://61475]=CUFP: print w/replies, xml ) Need Help??

This is a cheap and optimistic way of extracting numbers from text. It is quite easy to think of cases where this won't work, but there are tons of real-life cases where it works nicely. I allow for numbers at the end of sentences, like 1.23e3. I certainly don't handle expressions like 1.2+3.4-5.6. This was chosen for simplicity of the regex.

Update: Now also handles cases like "123ears" after reading Identifying and parsing numbers.

my @numbers= $text =~ /([-+\d.eE]*\d)/g;

Previous version was:

my @numbers= grep { s/\.$//; /\d/ } $text =~ /([-+\d.eE]+)/g;

Update: petral's excellent advice incorporated.

Replies are listed 'Best First'.
Re: Extract numbers
by petral (Curate) on Mar 01, 2001 at 08:25 UTC
    A slight fuss: [-+\d.eE]is probably a little faster than /i. (Though the regex engine is so smart it may figure out there's only one letter and do this anyway.)

    p

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (2)
As of 2024-04-24 14:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found