Number parser by regular expressons : Convert to Integer « Number « Ruby






Number parser by regular expressons


class NumberParser
  @@number_regexps = {
    :to_i => /([+-]?[0-9]+)/,
    :to_f => /([+-]?([0-9]*\.)?[0-9]+(e[+-]?[0-9]+)?)/i,
    :oct => /([+-]?[0-7]+)/,
    :hex => /\b([+-]?(0x)?[0-9a-f]+)\b/i
  }

  def NumberParser.re(parsing_method=:to_i)
    re = @@number_regexps[parsing_method]
    raise ArgumentError, "No regexp for #{parsing_method.inspect}!" unless re
    return re
  end

  def extract(s, parsing_method=:to_i)
    numbers = []
    s.scan(NumberParser.re(parsing_method)) do |match|
      numbers << match[0].send(parsing_method)
    end
    numbers
  end
end

p = NumberParser.new

pw = "104 and 391."
NumberParser.re(:to_i).match(pw).captures     
p.extract(pw, :to_i)                          
p.extract('$60.50', :to_f)                    
p.extract('AAA', :hex)
p.extract('017.', :oct)          
p.extract('From 0 to 10e60 AA -2.4 s')

 








Related examples in the same category

1.convert a floating-point number
2.convert a string
3.convert a binary number from a string
4.convert an octal number
5.convert a hexadecimal number
6.convert a character code
7.Converting Between Classes
8.ArgumentError: invalid value for Integer: "1001 nights"
9.Converting Between Characters and Values
10.Parsing A Number From A String
11.to_i gives the integer version of an object, and to_f gives the float version
12.Convert string to integer by parameter
13.Convert string to number with non number string