gsub and slash-ampersand in the substitution string

  • Thread starter Jani Patokallio
  • Start date
J

Jani Patokallio

Greetings,

I'm trying to do something that should be very simple: stick a "\" in
front of
every instance of "&" in a string. However, the obvious code...

"this&that".gsub!("&", "*")
--> "this*that" # OK!

"this&that".gsub!("&", "\\&")
--> "this&that" # Wrong

...doesn't work, because "\&" means "last match" in gsub substitution
strings.
How can I escape this? I experimentally determined that entering
"\\\\\\&"
(that's six backslashes) gets the desired result, but I don't really
understand why. Is there a less obscure way of doing this?

Cheers,
-jani
 
E

Esteban Manchado Velázquez

--/NkBOFFp2J2Af1nK
Content-Type: text/plain; charset=iso-8859-1
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

Greetings,
=20
I'm trying to do something that should be very simple: stick a "\" in=20
front of
every instance of "&" in a string. However, the obvious code...
=20
"this&that".gsub!("&", "*")
--> "this*that" # OK!
=20
"this&that".gsub!("&", "\\&")
--> "this&that" # Wrong
=20
...doesn't work, because "\&" means "last match" in gsub substitution=20
strings.
How can I escape this? I experimentally determined that entering=20
"\\\\\\&"
(that's six backslashes) gets the desired result, but I don't really
understand why. Is there a less obscure way of doing this?

I'm not sure, but I think that the problem is that you are using double
quotes. So, the value you are passing is really the same as:

'\\\&'

Which, once you interpret the escape sequences, you have a literal '\' and a
literal '&'...

--=20
Esteban Manchado Vel=E1zquez <[email protected]> - http://www.foton.es
EuropeSwPatentFree - http://EuropeSwPatentFree.hispalinux.es

--/NkBOFFp2J2Af1nK
Content-Type: application/pgp-signature; name="signature.asc"
Content-Description: Digital signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.5 (GNU/Linux)

iD8DBQFFKjrxhYgK5b1UDsERAlC8AJsFBEEKmaLIgyjCrc/sDYa+MD34ogCfchCt
HEx/oeI+zaBbLiX7BWDmd1c=
=Kypl
-----END PGP SIGNATURE-----

--/NkBOFFp2J2Af1nK--
 
J

Jan Svitok

this was discussed several times, try searching for gsub and \\ or
escaping or something similar. \& is the last match, and \\ is the
whole match. so you need to escape both. The correct solutions to this
'quiz' are posted somewhere, just google it ;-)
 

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,968
Messages
2,570,152
Members
46,698
Latest member
LydiaHalle

Latest Threads

Top