ruby regexp不止一次找到模式

时间:2014-07-17 14:49:21

标签: ruby regex string

value = "Men - $30, Women - $20"
# value = "Men - 0"
# value = "free"
data = /\$(\d*)/.match value

目前:

data.to_a
 => ["$30", "30"] 

我想:

data.to_a
 => ["$30", "30", "$20", "20] 

如何实现

1 个答案:

答案 0 :(得分:5)

使用String#scan

value = "Men - $30, Women - $20"

value.scan(/(\$(\d+))/)
# => [["$30", "30"], ["$20", "20"]]

value.scan(/(\$(\d+))/).flatten
# => ["$30", "30", "$20", "20"]