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')
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?
source share