私はまだ正確に何をしたいか分からないが、ここであなたを助ける必要がありますいくつかのコードです:
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
を使用するよりもより多くの仕事です。私はあなたが探しているものを完全に理解しているとは思えません。
コードを投稿できますか? –