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
···
--
Posted via http://www.ruby-forum.com/.
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 '&'...
···
On Mon, Oct 09, 2006 at 08:58:09PM +0900, Jani Patokallio wrote:
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?
--
Esteban Manchado Velázquez <zoso@foton.es> - http://www.foton.es
EuropeSwPatentFree - http://EuropeSwPatentFree.hispalinux.es
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
···
On 10/9/06, Esteban Manchado Velázquez <zoso@foton.es> wrote:
On Mon, Oct 09, 2006 at 08:58:09PM +0900, Jani Patokallio wrote:
> 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?
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 '&'...
--
Esteban Manchado Velázquez <zoso@foton.es> - http://www.foton.es
EuropeSwPatentFree - http://EuropeSwPatentFree.hispalinux.es