[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

replace a string delimited by 2 other string, regexp problem

Sébastien Maurette

10/2/2006 7:56:00 PM

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.
http://fr.mail...

3 Answers

Logan Capaldo

10/2/2006 8:16:00 PM

0

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/langua...

Vincent Fourmond

10/2/2006 8:19:00 PM

0


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

David Vallner

10/2/2006 9:40:00 PM

0

Vincent Fourmond 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 Vallner