Determine if a String is numeric using two regex's
Re: ruby equivalent PHP function is_numeric?
Posted by Jason Dusek (Guest) on 17.11.2006 18:58
On 11/17/06, Josselin wrote:
> After reading completely my Ruby book, I cannot find a function
> equivalent to the PHP is_numeric? to test a String
There is no such function, although you can pretty readily use regexes
to do it...
It really is too bad that String.to_f does not throw an exception - or
at least return NaN - when the string is not a number.
> myString.is_numeric? (check only digits and dot character)
A regex that matches the cases where String.to_f will find a value is
simple to write, and you can create String.numeric? like so:
not ( self =~ /^[[:digit:]]+(\.[[:digit:]]+)?([eE][[:digit:]]+)?/ or
self =~ /^\.[[:digit:]]+([eE][[:digit:]]+)?/ ).nil?