Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Floating Point/Integer Regular Expression

by shortyfw06 (Beadle)
on Jul 25, 2012 at 15:18 UTC ( #983684=perlquestion: print w/ replies, xml ) Need Help??
shortyfw06 has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to modify the following regular expression, which is for integers either negative or positive.

$_[0] =~ /^(?:|-|\d+|-\d+)$/

I'd like the regular expression to also capture floating point values either negative or positive. I thought this would work but it is not.

$_[0] =~ /^(?:|-|\d+|-\d+|\d+\.\d+|-\d+\.\d+)$/

Comment on Floating Point/Integer Regular Expression
Select or Download Code
Re: Floating Point/Integer Regular Expression
by tobyink (Abbot) on Jul 25, 2012 at 15:29 UTC

    Scalar::Util provides an excellent looks_like_number function.

    use Scalar::Util qw< looks_like_number >; use Test::More tests => 6; ok looks_like_number '1'; ok looks_like_number '123'; ok looks_like_number '-123'; ok looks_like_number '1.0'; ok looks_like_number '123.0'; ok looks_like_number '-123.0';

    View the source for Scalar::Util::PP - it's got a few regular expressions you could probably borrow.

    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

      Thank you. That is a useful function! I ended up answering my own question for a regex that includes negative/positive integers and negative/positive floating points.

      /^(?:|-|\d+|-\d+|\d+.|-\d+\.|\d+\.\d+|-\d+\.\d+)$/

      And just for clarification, this is used as a -validatecommand.

        Did you know that regexp matches:

        • -
        • 1.

        But fails to match:

        • .1
        • -.1

        You might want to try this. It's somewhat simpler than yours, and it disallows the single hyphen, but allows decimals which start with the decimal point and no preceding 0.

        /^[-]?(?:[.]\d+|\d+(?:[.]\d*)?)$/

        Or if you consider a leading/trailing decimal point to be an error, it can be made simpler:

        /^[-]?\d+(?:[.]\d+)?$/
        perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re: Floating Point/Integer Regular Expression
by moritz (Cardinal) on Jul 25, 2012 at 16:49 UTC

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (14)
As of 2015-07-02 08:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (31 votes), past polls