简体   繁体   中英

Replace keys of a hash with its value inside a specific group of a matched regex

I have an input:

input = gets

in which a substring of the form:

"本資料由(Name of a contractor)提供"

appears at different positions. I also have thousands of contractor names and their English transliterations stored in a hash:

hash = {'key1': 'value1', 'key2': 'value2'}

I have the following code:

input.gsub!(/本資料由(.+)提供/) {"\nThe following information has been provided by: #{$1}\n"} 
# => The following information has been provided by: (name of contractor)

To change a native name into English name, I can do:

person_making_announcement = /(The following information has been provided by: )(.+)/.match(input)
if Company_making_the_Announcement[2].match "key1"
  input.gsub! Company_making_the_Announcement[2], "value1"
elsif Company_making_the_Announcement[2].match "key2"
  input.gsub! Company_making_the_Announcement[2], "value2"
end

But this is very clumsy, and I need them in a hash anyways for other parts of the code. If I do:

hash.each do |k, v|
 input.gsub!("#{k}", "#{v}")
end

then all matches in input are changed. If I change the method to use sub! , only the first instance will be changed. I thought the following would work:

myregex = /(There is text here: )(.+)/.match(input)
hash.each do |k, v|
  myregex[2].gsub!("#{k}", "#{v}")
end

But it does not. I need to keep the regex since it is part of a substitution, and modification previously made on the input.

What would be the syntax to make the change only inside a specific subgroup in a regex matched to the input?

I think you may be after the following, but please tell me if I'm wrong.

def replace_em(str, h)
  str.gsub(/\S+/, Hash.new { |_,k| k }.merge(h))
end

h = { 'k1'=>'v1', 'k2'=>'v2' }
str = "Now is the k1 for all good persons to k2 to their friend k11"

replace_em(str, h)
  #=> "Now is the v1 for all good persons to v2 to their friend k11"

/\\S+/ matches strings of characters that contain no whitespace.

g = Hash.new { |_,k| k } 

creates an empty hash with a default proc that causes g[k] to return k if g does not have a key k .

g.merge(h)

returns a hash having the default proc just created with keys and values from h .

See the doc for the form of Hash::new that takes a second argument that is a hash.

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