如何从包含数字+字符的字符串中提取数字到Ruby中的数组?

Igg*_*ggy 1 ruby regex arrays string

我有包含整数和字符的字符串,我需要提取数组中的所有数字,例如:

str = "achance123for84faramir3toshowhis98quality"
#=> [123, 84, 3, 98] #Desired output
Run Code Online (Sandbox Code Playgroud)

我无法将它们组合在一起.我试过了:

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

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

如何维护所有整数的分组并将它们列在数组中?假定它将包含唯一的数字和字符(AZ).没有空格/非单词字符.所有人都会小一些.

(它们不必转换为整数.我只是遇到问题想出正则表达式将它们分组.如果有一个没有正则表达式的解决方案,那也太棒了!)

Ger*_*rry 7

尝试使用String#scan,像这样:

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

如果你想要整数而不是字符串,只需添加map它:

str.scan(/\d+/).map(&:to_i)
#=> [123, 84, 3, 98]
Run Code Online (Sandbox Code Playgroud)