How to extract numbers from string containing numbers+characters into an array in Ruby?

Viewed 4798

I have string that contains integers and characters and I need to extract all numbers in array, for example:

str = "achance123for84faramir3toshowhis98quality"
#=> [123, 84, 3, 98] #Desired output

I am having trouble grouping them together. I have tried:

str.split('').select {|el| el.match(/[\d]+.*/)}
#=> ["1", "2", "3", "8", "4", "3", "9", "8"]

str.split('').select {|el| el.match(/[\d]+[\D]+/)}
#=> []

How can I maintain the grouping for all integers and list them in array? Assume it will contain only numbers and characters (a-z). No whitespace/ non-word characters. All will be lowercased.

(they don't have to be converted to integer. I am just having problem coming up with the regex to separate them in groups. If there is a solution without Regex, that'd be awesome too!)

1 Answers

Try using String#scan, like this:

str.scan(/\d+/)
#=> ["123", "84", "3", "98"]

If you want integers instead of strings, just add map to it:

str.scan(/\d+/).map(&:to_i)
#=> [123, 84, 3, 98]
Related