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?0 個または 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 に答える