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)







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:
And, to easily turn the Strings returned by String#scan in to Integers and Floats, just do
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?
Hi Federico,
.5 is consider 0.5 in several countries. It is intentional.