8

我有一个带有不同货币数量的字符串,例如,

"454,54$", "Rs566.33", "discount 88,0$" etc.

模式不一致,我只想从字符串和货币中提取浮点数。

我如何在 Ruby 中实现这一点?

4

2 回答 2

19

您可以使用此正则表达式来匹配您发布的两种格式的浮点数:-

(\d+[,.]\d+)

请参阅Rubular 上的演示

于 2012-12-04T15:53:11.123 回答
8

你可以试试这个:

["454,54$", "Rs566.33", "discount 88,0$", "some string"].each do |str|
  # making sure the string actually contains some float
  next unless float_match = str.scan(/(\d+[.,]\d+)/).flatten.first
  # converting matched string to float
  float = float_match.tr(',', '.').to_f
  puts "#{str} => %.2f" % float
end

# => 454,54$ => 454.54
# => Rs566.33 => 566.33
# => discount 88,0$ => 88.00

CIBox 演示

于 2012-12-04T15:55:09.743 回答