replace a string delimited by 2 other string, regexp problem

  • Thread starter Sébastien Maurette
  • Start date
S

Sébastien Maurette

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.yahoo.com
 
V

Vincent Fourmond

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
 
D

David Vallner

--------------enig817FD8C1571506A4A77A1FC8
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable

Vincent said:
left =3D "/*startdel2*/"
right =3D "/*enddel2*/"
p str.gsub(/#{Regexp.quote(left)}(.*?)#{Regexp.quote(right)}/m,
"#{left}hello#{right}")
=20

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)}(.*?)(?=3D#{Regexp.quote(right)})/m,
"#{left}hello")

David Vallner


--------------enig817FD8C1571506A4A77A1FC8
Content-Type: application/pgp-signature; name="signature.asc"
Content-Description: OpenPGP digital signature
Content-Disposition: attachment; filename="signature.asc"

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.5 (MingW32)

iD8DBQFFIYdFy6MhrS8astoRAvxwAJsFcYS3yog/SDsLRa7p3UfnKf1HNwCfZ5Jm
l3f8M6Ou5SQFqXFgIe1WrZY=
=feCN
-----END PGP SIGNATURE-----

--------------enig817FD8C1571506A4A77A1FC8--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top