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

Greetings, i have been looking for a better way to write a regex for determining if a string is a number, including integers, floating pt numbers, and scientific notation. seems so obfuscated that it has to be wrong. please point out errors, omissions, etc. so far, i have looked at cpan and the perlmonks archive. i have only found regexs for more well-behaved strings. the output i need to parse includes (some of these are ill-formed, but "it's a liven'!":
1.0 -1.0 .9 9. -.9 -.4e08 +4.E-08 +.2e+219 2.00001e+9
the code that i have and not sure about is:
our $numregex = qr/^ # may have leading plus or minus [-+]? # one of these formats must exist (?: # maybe one or more digits, then decimal, and maybe more dig +its \d+\.?\d* # or decimal followed by one or more digits |\.\d+ ) # optional sci notation (?: # "e" or "E" and plus or minus, and one, two, or three digit +s [eE][-+]\d{1,3} )? $/x;
thank you.

Replies are listed 'Best First'.
Re: number regex (incl sci notation)
by VSarkiss (Monsignor) on Dec 07, 2004 at 19:21 UTC
      thanks for the assist. i had forgotten about the "perldoc -q" thing. also, the Scalar::Util qw( looks_like_number ) works wonderfully in my quick testing. thanks again.

      Scalar::Util's looks_line_number() routine checks the Perl API Looks Like Number field in the scalar.

      In some cases your variable might have a string which is a valid number, but doesn't have that field set.

        There is no "looks like a number field" in a scalar. looks_like_number() checks whether a *string* *looks like a number*. This is independent of whether the scalar has an IV stored in it (which appears to be what you are thinking of).

        - tye        

Re: number regex (incl sci notation)
by Anonymous Monk on Dec 07, 2004 at 23:57 UTC