1

我有一个像这样的字符串:

str = 'in europe it costs 250 eur'

或者:

str = 'in europe it costs a lot (250eu)'

或者:

str = 'eureka! I found it and it costs eu250'

或者:

str = 'eureka! I found it and it costs 250.00eur'

等等..

当它们后面和前面有一个非字符 ( ) 时,我想替换两者'eu',但我不希望它们成为替换的受害者。我如何使用或其他方法完成该任务?'eur''euro'[^a-z]sub

4

1 回答 1

1

首先,我们编译一个用作测试用例集的数组:

test_input = ["aa 250 eu", "bb 250eu", "cc 250 euro", "dd 250euro", 
              "ee eu 250", "ff eu250",  "gg eur250",  "hh euro250"]

接下来我们试试正则表达式:

puts test_input.map { |s| 
  # First gsub handles eur before number, second gsub handles eur after number
  s.gsub(/(eu|euro?)\s?(\d+)/, 'euro \2').
    gsub(/(\d+)\s?(eu|euro?)(\z|\s)/, '\1 euro') 
}

解释:

  • \d+匹配 1 个或多个数字(数字)
  • \s?匹配零个或 1 个空格
  • \z 匹配字符串结尾

结果:

aa 250 euro
bb 250 euro
cc 250 euro
xx 250 euro
dd euro 250
ee euro 250
ff euro 250
于 2012-06-08T02:27:40.500 回答