From: Ammar Ali Date: 2010-11-21T07:41:15+09:00 Subject: Re: gsub and backslashes On Sun, Nov 21, 2010 at 12:34 AM, Ammar Ali wrote: > On Sun, Nov 21, 2010 at 12:13 AM, Ralph Shnelvar wrote: >> Consider the string >>  \1\2\3 >> that is >>  "\\1\\2\\3" >> >> I feel really stupid ... but this simple substitution pattern does not do what I expect. >> >>  "\\1\\2\\3".gsub(/\\/,"\\\\") >> >> What I want is to change single backslashes to double backslashes.  The result of the above substitution is "no change" >> >> On the other hand >>  "\\1\\2\\3".gsub(/\\/,"\\\\\\\\") >> does do what I want ... but I am clueless as to why. > > Backslashes are tricky. What's happening here is each escaped > backslash "\\" yields one backslash, which affects (escapes) what > comes after it, in this case another escaped backslash that in turn > yields one back slash. In other words, four backslashes yield two > backslashes, which is an escaped backslash (i.e one backslash). > I should have added that you can get the same result with 3 backslashes. So 6 of them will give you two. >> "\\1\\2\\3".gsub(/\\/,"\\\\\\").scan /./ => ["\\", "\\", "1", "\\", "\\", "2", "\\", "\\", "3"] Regards, Ammar