Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

regex for numbers

by BernieC (Pilgrim)
on Apr 07, 2021 at 15:47 UTC ( [id://11130959]=perlquestion: print w/replies, xml ) Need Help??

BernieC has asked for the wisdom of the Perl Monks concerning the following question:

This must be easy, but... I have to keep chasing number formats in a regex ---first was to allow a decimal, then to allow a negative number.. I've just run into "2.5e-05". I can hack that into my regex, but I'm wondering if there's a "standard" regex that can deal with all the various number formast?

Replies are listed 'Best First'.
Re: regex for numbers
by choroba (Cardinal) on Apr 07, 2021 at 15:50 UTC
    See looks_like_number in Scalar::Util.

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
Re: regex for numbers
by haukex (Archbishop) on Apr 07, 2021 at 15:49 UTC
Re: regex for numbers
by hippo (Bishop) on Apr 07, 2021 at 16:11 UTC
Re: regex for numbers
by BernieC (Pilgrim) on Apr 07, 2021 at 17:00 UTC
    Thanks for all the obvious things I missed [but seeing the regexes that do the job, I can see why it was tricky to do it by starting with "\d+" Odd - I guessed there was a module that'd do it, and I searched CPAN for "number" and it delivered a lot of modules and the Regexp module didn't show up {what mostly showed up were modules for messing with international phone numbers. :o)} Doesn't matter I guess THANKS ALL!!
Re: regex for numbers
by hrcerq (Scribe) on Apr 07, 2021 at 21:18 UTC

    This comment might be a bit late, but anyway... coincidentally, I read yesterday an example in perlretut, which addresses precisely this question. The final solution is the same as presented in the FAQ, by the way.

Re: regex for numbers
by Discipulus (Canon) on Apr 07, 2021 at 17:30 UTC
    Hello BernieC,

    you got obvious and wise answers; I'm not here for this :) What about { local $@; eval 0 + $maybe_a_number ... }?

    L*

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
      Perl happily accepts 0 + '1.1.' (well, it warns, but it doesn't throw an exception). So, eval alone isn't enough.

      map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (4)
As of 2024-04-25 05:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found