Determine If A String Is Numeric Using Two Regex's In Ruby
Join the DZone community and get the full member experience.Join For Free
Determine if a String is numeric using two regex's http://www.ruby-forum.com/topic/88507 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:
class String def numeric? not ( self =~ /^[[:digit:]]+(\.[[:digit:]]+)?([eE][[:digit:]]+)?/ or self =~ /^\.[[:digit:]]+([eE][[:digit:]]+)?/ ).nil? end end
Opinions expressed by DZone contributors are their own.