Brady
Brady

Reputation: 41

Regex replace expression in Ruby on Rails

I need to replace some text in a db field based on a regex search on a string.

So far, I have this:

foo = my_string.gsub(/\[0-9\]/, "replacement" + array[#] + "text")

So, I'm searching in the field for each instance of a number surrounded by brackets ([1],[2],etc.). What I would like to do is find each number (within the brackets) in the search, and have that number used to find the specific array node.

Any ideas? Let me know if anyone needs any kind of clarification.

Upvotes: 4

Views: 7397

Answers (1)

mu is too short
mu is too short

Reputation: 434595

The easiest would be to use the block form of gsub:

foo = my_string.gsub(/\[(\d+)\]/) { array[$1.to_i] }

And note the capture group inside the regex. Inside the block, the global $1 is what the first capture group matched.

You could also use a named capture group but that would require a different global because $~ is (AFAIK) the only way to get at the current MatchData object inside the block:

foo = my_string.gsub(/\[(?<num>\d+)\]/) { |m| a[$~[:num].to_i] }

For example:

>> s = 'Where [0] is [1] pancakes [2] house?'
=> "Where [0] is [1] pancakes [2] house?"
>> a = %w{a b c}
=> ["a", "b", "c"]

>> s.gsub(/\[(\d+)\]/) { a[$1.to_i] }
=> "Where a is b pancakes c house?"

>> s.gsub(/\[(?<num>\d+)\]/) { |m| a[$~[:num].to_i] }
=> "Where a is b pancakes c house?"

Upvotes: 10

Related Questions