我還是不知道你想要什麼,但這裏的一些代碼,應該可以幫助您:
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
清楚更多的工作。我不確定我完全理解你在找什麼,爲什麼你認爲它會更容易。
你可以發佈你的代碼嗎? –