如何将数字从字符串中提取到单独的数组中

时间:2021-10-19 20:07:27

Given this string

鉴于此字符串

"In 2015, I want to know how much does iPhone 6+ cost?"

how can I return [2015, 6]?

我该怎么回复[2015,6]?

My first attempt at this was

我的第一次尝试是

numbers = str.tr("^0-9", '')

but that produces 20156.

但这产生了20156。

2 个解决方案

#1


8  

You can use scan:

你可以使用扫描:

numbers = str.scan(/\d+/)
# => ["2015", "6"]

#2


1  

scan is better, but this also works.

扫描更好,但这也有效。

"In 2015, I want to know how much does iPhone 6+ cost?".gsub(/\D/,' ').split
  #=> ["2015", "6"] 

#1


8  

You can use scan:

你可以使用扫描:

numbers = str.scan(/\d+/)
# => ["2015", "6"]

#2


1  

scan is better, but this also works.

扫描更好,但这也有效。

"In 2015, I want to know how much does iPhone 6+ cost?".gsub(/\D/,' ').split
  #=> ["2015", "6"]