2012-01-23 6 views
1

$ 1を設定する正規表現があります:()の間のテキストに対応します:the_beginning(.*)the_end文字列をregexpに置き換えます

すべての正規表現ではなく、$ 1に対応する値をsomethingelseに置き換えます。実際の文脈で

my_stringは含まれています

/* MyKey */ = { [code_missing]; MY_VALUE = "123456789"; [code_missing]; }

私が(例えば、 "987654321" で) "123456789" を交換したいです。 そして、これは私の正規表現です:

"/\\* MyKey \\*/ = {[^}]*MY_VALUE = \"(.*)\";"

+1

コードを投稿できますか? –

答えて

3

私はまだ正確に何をしたいか分からないが、ここであなたを助ける必要がありますいくつかのコードです:

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を使用するよりもより多くの仕事です。私はあなたが探しているものを完全に理解しているとは思えません。

+0

右ですが、左右の部分をコピーするのではなく、直接編集できるクリーンなバージョンがありますか? – louiscoquio

+0

'p str.sub /(the_beginning).+((the_end)/、 '\ 1new middle \ 2''のように" 123456789 "を置き換えたいだけです。私はちょうどそこに良い解決策があると思っていた – louiscoquio

+0

@ louiscoquioああ、私はあなたのために編集させてください。 – Phrogz

関連する問題