Meditations on programming, startups, and technology
New Relic

How to parse decimal numbers within a string

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 Newsletter and/or Feed.

receive my posts by email

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

  1. Tore Darell says:

    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

   {|n| n.include?('.') ? n.to_f : n.to_i}
  2. federico says:

    Isn’t more correct something like:


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

  3. Hi Federico,
    .5 is consider 0.5 in several countries. It is intentional. 😉

Copyright © 2005-2014 Antonio Cangiano. All rights reserved.