Poochie
Poochie

Reputation: 45

How do I use a Regex search and replace?

I have a string like:

str = 'in europe it costs 250 eur'

or:

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

or:

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

or:

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

and so on..

I want to replace both 'eu' and 'eur' with 'euro' when they are followed and preceded by a non-char ([^a-z]) but I don't want them to be victims of replacement. How do I accomplish that using sub or other methods?

Upvotes: 1

Views: 120

Answers (1)

Casper
Casper

Reputation: 34308

First we compile an array we use as the set of test cases:

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

Next we try out the 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') 
}

Explanation:

  • \d+ matches 1 or more digits (number)
  • \s? matches zero or 1 whitespace
  • \z matches end of string

Result:

aa 250 euro
bb 250 euro
cc 250 euro
xx 250 euro
dd euro 250
ee euro 250
ff euro 250

Upvotes: 1

Related Questions