Morph AppSpace - Platform as a Service for RoR

How to parse decimal numbers within a string

Antonio Cangiano February 5th, 2006

INPUT: a string containing decimal numbers.

OUTPUT: an array containing all the decimal numbers within the given string.

You can accomplish this task very quickly with the String#scan method and the right Regular Expression (regex).

Given a string s, you can use:

numbers = s.scan /[-+]?\d*\.?\d+/

numbers will be an array whose elements are the decimal numbers within the string s. Note how the regex considers the possible + or – signs in front of the numbers.

If you also wish to match floating point numbers with exponents (scientific notation, e.g. 2.54.e-07), then use the following:

numbers = s.scan /[-+]?\d*\.?\d+([eE][-+]?\d+)?/ 


If you enjoyed this post, then make sure you subscribe to my RSS Feed.

  • Mathematics , Quick Tips
  • Comments(3)

3 Responses to “How to parse decimal numbers within a string”

  1. Tore Darell NORWAYon 12 Feb 2006 at 7:00 pm

    Nice. I found I had to make the matching group in the second regex non-capturing, though, as the String#scan method would only return arrays of group matches if they’re present (containing nil if it wasn’t scientific notation), but this worked on both “classic” numbers and numbers written with scientific notation:

    
        numbers = s.scan /[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?/
    

    And, to easily turn the Strings returned by String#scan in to Integers and Floats, just do

    
        numbers.map{|n| n.include?('.') ? n.to_f : n.to_i}
    
  2. federico ITALYon 02 May 2006 at 5:43 am

    Isn’t more correct something like:

    /[+-]?\d+(\.\d+)?/

    Since your regexp will match something like .5 without any digit before the decimal point… or it’s that what you want? :)

  3. Antonio Cangiano CANADAon 03 May 2006 at 9:37 am

    Hi Federico,
    .5 is consider 0.5 in several countries. It is intentional. ;-)