Afficher un message
Vieux 22/02/2008, 18h48   #4
Rob Biedenharn
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: gsub("\\", "\\\\") seems unintuitive

On Feb 22, 2008, at 12:27 PM, John Woods wrote:
> The following confusing behavior is noted in the pickaxe book (2nd
> ed) on page 75:
>
> # I would expect two backslashes in the result
> irb> puts "\\".gsub("\\","\\\\")
> \
>
> # I would expect four backslashes in the result
> irb> puts "\\".gsub("\\","\\\\\\\\")
> \\
>
> I can certainly work around it, but it seems unintuitive. Is there a
> reason why gsub behaves this way? Just curious...



Notwithstanding the earlier responses...

Since the replacement string is evaluated 'twice', once as a ruby
string literal and then again by gsub to look for group refrences like
'\1', you need to provide two levels of escaping for a backslash.

\ is "\\"
so two of them is "\\\\"
and you want gsub to see that so it need to have them escaped: "\\\\\\
\\"

Whew! Yeah, it's unfortunate, but backslash is doing double-duty
here: introducing a group reference to the regular expression and
escaping characters in a string literal (just like "\n", but also
itself).

-Rob

Rob Biedenharn http://agileconsultingllc.com
Rob@AgileConsultingLLC.com


  Réponse avec citation
 
Page generated in 0,05243 seconds with 9 queries