Ruby, readable & self-documenting Regex composition


  • 0
    K
    def is_number(s)
        numeric_string_regex === s
    end
    
    def numeric_string_regex
        @numeric_string_regex ||= begin
            natural = /\d+/
            decimal = /#{natural.source}\.?(#{natural.source})?/
            dot_natural = /\.#{natural.source}/
            
            sign = /[+-]?/
            float = /#{sign.source}(#{decimal.source}|#{dot_natural.source})/
            exp = /e#{sign.source}#{natural.source}/
            numeric = /#{float.source}(#{exp.source})?/
            
            /\A *#{numeric.source} *\z/
        end
    end
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.