I'm still not sure exactly what you want, but here's some code that should help you:
str = "Hello this is the_beginning that comes before the_end of the string"
p str.sub /the_beginning(.+?)the_end/, 'new_beginning\1new_end'
#=> "Hello this is new_beginning that comes before new_end of the string"
p str.sub /(the_beginning).+?(the_end)/, '\1new middle\2'
#=> "Hello this is the_beginningnew middlethe_end of the string"
Edit:
theDoc = '/* MyKey */ = { [code_missing]; MY_VALUE = "123456789";'
regex = %r{/\* MyKey \*/ = {[^}]*MY_VALUE = "(.*)";}
p theDoc[ regex, 1 ] # extract the captured group
#=> "123456789"
newDoc = theDoc.sub( regex, 'var foo = \1' )
#=> "var foo = 123456789" # replace, saving the captured information
Edit #2: Getting access to information before/after a match
regex = /\d+/
match = regex.match( theDoc )
p match.pre_match, match[0], match.post_match
#=> "/* MyKey */ = { [code_missing]; MY_VALUE = \""
#=> "123456789"
#=> "\";"
newDoc = "#{match.pre_match}HELLO#{match.post_match}"
#=> "/* MyKey */ = { [code_missing]; MY_VALUE = \"HELLO\";"
Note that this requires a regex that does not actually match the pre/post text.
If you need to specify the limits, and not the contents, you can use zero-width lookbehind/lookahead:
regex = /(?<=the_beginning).+?(?=the_end)/
m = regex.match(str)
"#{m.pre_match}--new middle--#{m.post_match}"
#=> "Hello this is the_beginning--new middle--the_end of the string"
…but now this is clearly more work than just capturing and using \1 and \2. I'm not sure I fully understand what you are looking for, why you think it would be easier.