How can I replace the regex as a string pattern?

So here is the script. I have a custom regular expression stored in my_regex variable. I should not have any other knowledge besides the fact that he has a named group called id . For example, one valid regex could be:

 my_regex = /ABC(?<id>...)ABC/ 

I am trying to do this: match this regular expression with a string and substitute the id group with the fixed string '123' . For instance:

 my_func(my_regex, 'ABC789ABCQQQQ') #=> 'ABC123ABCQQQQ' 

Now I know that this could be done if I myself defined the regular expression, for example, I could define my_regex as /(ABC)(...)(ABC)/ and just use

 my_match_data = my_regex.match('ABC789ABCQQQQ') result = my_match_data.captures[0] + '123' + my_match_data.captures[2] 

However, besides the fact that I am not the one who defines it, this solution is ugly and not generalizable. What if, instead of a single id , I have id1 , id2 and id3 , in random order?

I was looking for something as elegant as a string pattern for regular expression, for example, imagine:

 result = my_regex.match('ABC789ABCQQQQ') % {id: '123'} 

Is there a way to achieve this in a similar way?

+4
source share
2 answers

Well, I still cannot find a built-in solution for this. So, here is a simple extension that achieves something close.

 class MatchData def %(hash) string_copy = string.dup hash.each do |key, value| string_copy[self.begin(key)..self.end(key)] = value end string_copy end end my_regex = /ABC(?<id>...)ABC/ puts my_regex.match('ABC789ABCQQQQ') % {id: '123'} 
0
source

You can do this:

 regex = /1(?<cat>[az]+)2ABC(?<id>\d+)ABC/ str = '21dog2ABC789ABCQQQQ' name = :id replacement = '123' m = regex.match(str) #=> #<MatchData "1dog2ABC789ABC" cat:"dog" id:"789"> i = m.begin(name) #=> 9 str[0,i] + replacement + str[i+m[name].size..-1] #=> "21dog2ABC123ABCQQQQ" 
0
source

All Articles