正则表达式匹配Ruby中数百和数千的值

时间:2013-07-09 14:41:06

标签: ruby-on-rails ruby regex

我正在尝试找到一个有效的正则表达式,它允许我查找网页的所有价格,例如1,150.00500.00

这个正则表达式在Rubular中适用于我:

/(\d?,?\d+.\d+)/

但它在我的Ruby代码中不起作用,因为数百个值可以使用,但只需要数千个中的第一个数字(例如,在1,150.00中取1)。

我有什么遗失的吗?

这是我正在使用的代码:

str_rooms_prices = rooms_container.scan(/[\d,]?\d+\.\d+\s/)

puts "This is the room prices I've found so far #{str_rooms_prices}."

str_rooms_prices = str_rooms_prices - ["0"]

puts "I'm now substracting the 0 prices and this is what remains: #{str_rooms_prices}."

int_rooms_prices = str_rooms_prices.map { |str| str.to_i }

min_price = int_rooms_prices.min.to_i

然后我得到的min_price是1。

2 个答案:

答案 0 :(得分:3)

我认为你的正则表达式过于复杂。我认为/[\d,.]+/会做得很好。此外,您使用的to_i会因逗号

而中断
'1,000,000.00'.to_i
#=> 1

因此您需要先删除这些逗号,例如使用String#delete

'1,000,000.00'.delete(',').to_i
#=> 1000000

to_i的另一个问题是,它将丢弃小数位,因为它将数字转换为整数:

'1.23'.to_i
#=> 1

因此您应该使用to_f代替:

'1.23'.to_f
#=> 1.23

这是一个甚至可以处理负值的完整示例:

str = "Subtracting 1,500.00 from 1,150.23 leaves you with -350.77"
str.scan(/-?[\d,.]+/).map{|s| s.delete(',').to_f }
#=> [1500.0, 1150.23, -350.77]

如果您确实不需要小数位,当然请使用to_i

答案 1 :(得分:2)

由于您的转化min_price,您获得了to_i 1。

'1,150.00'.to_i
=> 1

尝试以下方法:

int_rooms_prices = str_rooms_prices.map { |str| str[0].tr(',','').to_i }

重要的是要注意您应该将价格转换为单位,否则小数位将丢失。因此,使用to_f将值转换为单位,然后乘以100得到完整值,然后就可以转换为整数。

int_rooms_prices = str_rooms_prices.map { |str| (str[0].tr(',','').to_f*100).to_i }

然后您可以使用number_to_currency来显示正确的价格,如下所示:

number_to_currency(min_price/100)