Replace a string delimited by 2 other string, regexp problem

Hello,

I want to replace a string in a file who is delimited by 2 other string.
My problem is to find the start and the end string delimiter and replace
the content between both.

Ex:
str = " /* startdel1 */ text1 text1 text1 /enddel1/ /startdel2/
text2 text2 text2 /enddel2/ /startdel3/ text3 text3 text3
/enddel3/ "

In this example i’want to replace the string /startdel2/ text2 text2
text2 /enddel2/
by

/startdel2/ hello /enddel2/

i’m newbie and it’s a real problem for me to do that.
help me
thx


Yahoo! Mail réinvente le mail ! Découvrez le nouveau Yahoo! Mail et son
interface révolutionnaire.

On Tue, Oct 03, 2006 at 04:55:44AM +0900, S?bastien Maurette wrote:

Hello,

I want to replace a string in a file who is delimited by 2 other string.
My problem is to find the start and the end string delimiter and replace
the content between both.

Learn about regular expressions, and then look into the gsub method of
String. You can get a very brief intro to regular expressions here:
http://ruby-doc.org/docs/ProgrammingRuby/html/language.html#UJ

Hello !

Ex:
str = " /* startdel1 */ text1 text1 text1 /enddel1/ /startdel2/
text2 text2 text2 /enddel2/ /startdel3/ text3 text3 text3
/enddel3/ "

In this example i’want to replace the string /startdel2/ text2 text2
text2 /enddel2/
by

/startdel2/ hello /enddel2/

left = “/startdel2/”
right = “/enddel2/”
p str.gsub(/#{Regexp.quote(left)}(.*?)#{Regexp.quote(right)}/m,
“#{left}hello#{right}”)

You need the /m as there might be newlines in the match, and you need
the Regexp.quote as your strings contain characters which lose their
usual meaning in a regexp (*).

Cheers !

Vince

Vincent F. wrote:

left = “/startdel2/”
right = “/enddel2/”
p str.gsub(/#{Regexp.quote(left)}(.*?)#{Regexp.quote(right)}/m,
“#{left}hello#{right}”)

The “right” could be in a positive lookahead making things probably a
likkle bit faster. No lookbehinds until Ruby 1.9 / 2.0 though.

p str.gsub(/#{Regexp.quote(left)}(.*?)(?=#{Regexp.quote(right)})/m,
“#{left}hello”)

David V.