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+)?/
Get more stuff like this
Subscribe to my mailing list to receive similar updates about programming.
Thank you for subscribing. Please check your email to confirm your subscription.
Something went wrong.