This post originated from an RSS feed registered with Ruby Buzz
by Antonio Cangiano.
Original Post: How to parse decimal numbers within a string
Feed Title: Zen and the Art of Ruby Programming
Feed URL: http://programmingzen.com/category/ruby/feed/
Feed Description: Antonio Cangiano's blog about Ruby development.
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: