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?
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]
| [reply] [d/l] [select] |
Re: regex for numbers
by haukex (Archbishop) on Apr 07, 2021 at 15:49 UTC
|
| [reply] |
Re: regex for numbers
by hippo (Bishop) on Apr 07, 2021 at 16:11 UTC
|
| [reply] |
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!! | [reply] |
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.
| [reply] |
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.
| [reply] [d/l] |
|
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]
| [reply] [d/l] [select] |
|
| [reply] [d/l] [select] |
|
|