Tracey Beauchat Tracey Beauchat - 5 months ago 17
Ruby Question

Replacing expression matches in Ruby with a table look up

I have a large string of text and am using a regex to search for a certain delimited string key. For example, I am interested in finding all occurrences of [!v some_word] in the text. I already have the regex to find the occurrences. What I want to do is use the found "some_word" to look up a value in a database and replace the whole occurrence "[!v some_word]" with the value I found. Is there a way to do this as a one liner using regex's? And as a catch..."some_word" might not be defined in the database, and in those cases I would want to ignore the match and just leave it.

My regex is: /([!v\s+([a-z\d_]+)\s*])/

The text would contain something like: "This proposal is created for [!v client_name]. As such [!v client_name] maintains personal rights..." The database would contain an entry keyed by "client_name" whose value might be "Google". So I want to be able to find all instances as marked by the [!v...], determine the key (e.g., client_name), and then replace the [!v...] with the value associated with that key. You could also assume that the value could be looked up through some association or even in a parameter array.


Yes. Use the form of String#gsub or String#gsub! that takes a block. The block will receive the match data as its parameters. You can put arbitrary code in the block that does a database query. The block should return a string, which will then be used to replace the portion of the text that matched the regex. The g in gsub stands for global, so it will process all matching parts of the string, not the just first one.

new_test = test.gsub(regex_pattern) do |match|
  # do database query
  # return a string