## extract decimal numbers from a string

Expand Messages
• Hi, I want to extract decimal numbers from a string which contains blanks. There can be 0-2 such numbers inside the string. How to do this? I tried the
Message 1 of 2 , Jul 1, 2003
Hi,
I want to extract decimal numbers from a string which contains blanks.
There can be 0-2 such numbers inside the string.
How to do this?
I tried the following:

/[0-9]+\.[0-9]+/;
\$num1=\$&;

# first number gets extracted properly

@fields=split('\$num1',\$_);

\$n=@fields;

# \$n=0 why?
I want to know a nice way to this..
Mukta
• From: Mukta Telang ... Don t use \$&. /([0-9]+ .[0-9]+)/; \$num1=\$1; See \$& section in perldoc perlvar (\$one, \$two) = /([0-9]+ .[0-9]+)/g;
Message 2 of 2 , Jul 2, 2003
From: Mukta Telang <mukta@...>
> Hi,
> I want to extract decimal numbers from a string which contains blanks.
> There can be 0-2 such numbers inside the string. How to do this? I
> tried the following:
>
> /[0-9]+\.[0-9]+/;
> \$num1=\$&;

Don't use \$&.

/([0-9]+\.[0-9]+)/;
\$num1=\$1;

See \$& section in
perldoc perlvar

(\$one, \$two) = /([0-9]+\.[0-9]+)/g;

or if you don't know how many numbers there'll be:

@numbers = /([0-9]+\.[0-9]+)/g;

The other problem is that this only accepts numbers with the decimal
part. If you also want to catch whole numbers you will want to change
the regexp to

@numbers = /([0-9]+(?:\.[0-9]+)?)/g;

HTH, Jenda
===== Jenda@... === http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery
Your message has been successfully submitted and would be delivered to recipients shortly.