是否有一个优雅的正则表达式方式使用Ruby将字符串中所有出现的°C替换为°F(同时转换单位)?例如:
“今天是25°C,明天是27°C。”
应该会产生类似的结果:
“今天是77°F,明天是81°F。”
答案 0 :(得分:3)
# -*- encoding : utf-8 -*-
def c2f(c)
c*9.0/5+32
end
def convert(string)
string.gsub(/\d+\s?°C/){|s| "#{c2f(s[/\d+/].to_i)}°F"}
end
puts convert("Today it is 25°C and tomorrow 27 °C.")
# result is => Today it is 77.0°F and tomorrow 80.6°F.
答案 1 :(得分:1)
String#gsub
的阻止形式看起来就像你需要的那样:
s = "Today it is 25C and tomorrow 27 C." #
re = /(\d+\s?C)/ # allow a single space to be present, need to include the degree character
s.gsub(re) {|c| "%dF" % (c.to_f * 9.0 / 5.0 + 32.0).round } #=> "Today it is 77F and tomorrow 81F."
我已经失去了学位角色(我使用的是Ruby 1.8.7,它不是非常适合Unicode)但希望这应该足以看出可能的内容。