Velocity Reviews > Perl > Regular Expression for Integer and float values

# Regular Expression for Integer and float values

Roop
Guest
Posts: n/a

 08-17-2006
Hello All

I want to use such regular expression which only allow integers and
float value.
for example :--

12
12.34
23.456
0.5
0.0
0

expression for that

with regards
Tarun sinha

Klaus
Guest
Posts: n/a

 08-17-2006
Roop wrote:
> I want to use such regular expression which only allow integers and
> float value.

see Perlfaq 4:
How do I determine whether a scalar is a number/whole/integer/float?

axel@white-eagle.invalid.uk
Guest
Posts: n/a

 08-17-2006
Roop <(E-Mail Removed)> wrote:

> I want to use such regular expression which only allow integers and
> float value.
> for example :--

> 12
> 12.34
> 23.456
> 0.5
> 0.0
> 0

> expression for that

Lets take this step by step... based on your examples...

m/^\d+ # At least one digit (and nothing else) to start the value
(?: # Start a cluster but don't capture
\.\d+ # We may have a decimal point followed by at least one digit
)? # The decimal point + following digits may occur either
# once or not at all
\$ # Nothing else can follow
/x; # And allow whitespace and comments in the RE

This allows all your examples, but not for example: 5.
as it does not have a following digit.

Axel

Dave
Guest
Posts: n/a

 08-17-2006

"Roop" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed) ups.com...
> Hello All
>
> I want to use such regular expression which only allow integers and
> float value.
> for example :--
>
> 12
> 12.34
> 23.456
> 0.5
> 0.0
> 0
>
> expression for that
>
>
> with regards
> Tarun sinha
>

Look at the cpan module Regexp::Common. Better than re-inventing the wheel
unless you have unusual constraints.

Something like:
use Regexp::Common;
my \$NUMBER = \$RE{num}{real}{-keep};
# later
my (\$number) = \$input =~ \$NUMBER;

but read the docs to get just what you want.

Advise based on Perl Best Practices p263