Feb
5
How to parse decimal numbers within a string
By Antonio Cangiano. Filed under Mathematics, Quick Tips
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+)?/
Related Articles:
- Comparing the performance of IronRuby, Ruby 1.8 and Ruby 1.9 on Windows
- Improve the speed and security of your SQL queries
- Do Androids Count Electric Sheep with DB2 or MySQL?
- Why MacRuby Matters (Present & Future)
- Canadians, fight Internet Usage Based Billing (UBB)
If you enjoyed this post, then make sure you subscribe to our RSS Feed.
Comments
3 Responses to “How to parse decimal numbers within a string”























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.