我还是不知道你想要什么,但这里的一些代码,应该可以帮助您:
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"
编辑:
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
编辑#2:访问信息息前/匹配
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\";"
注意,这需要一个正则表达式实际上不匹配的前/后的文本之后。
如果你需要指定范围,而不是内容,可以使用零宽度回顾后/前瞻:
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"
......但现在这不仅仅是收集和利用\1
和\2
清楚更多的工作。我不确定我完全理解你在找什么,为什么你认为它会更容易。
你可以发布你的代码吗? –