简体   繁体   中英

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 ( [^az] ) but I don't want them to be victims of replacement. How do I accomplish that using sub or other methods?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM