如何使用正则表达式搜索并替换?

时间:2012-06-08 01:54:05

标签: ruby regex

我有一个字符串:

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',当它们被跟随并且前面有非char([^a-z])但我不想要它们成为替代的受害者。如何使用sub或其他方法实现这一目标?

1 个答案:

答案 0 :(得分:1)

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

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

接下来我们试试regexps:

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