From: Brian Candler Date: 2007-02-22T04:50:28+09:00 Subject: Re: Weird behaviour escaping special characters in a string On Thu, Feb 22, 2007 at 02:55:09AM +0900, Greg Hurrell wrote: > Why do I need so many backslashes in my replacement expression? > > There are five slashes in the replacement expression: > > gsub(/(\\|')/, '\\\\\1') > > But I would have thought that three would work: > > gsub(/(\\|')/, '\\\1') Because even in single quotes, blackslashes must be doubled; this in turn is because \' is the way that you insert a single quote within a single-quoted string. irb(main):001:0> a='\\' => "\\" irb(main):002:0> a.size => 1 irb(main):003:0> b='\'' => "'" irb(main):004:0> b.size => 1 irb(main):005:0> c='\x' => "\\x" irb(main):006:0> c.size => 2 > I basically want to replace "whatever is found in the pattern" with a > backslash (\\) followed by "whatever was found" (\1); so that's three > slashes. But with only three slashes Ruby gives me \1foo\1 instead of > \'foo\'. Four slashes produces the same result. Five slashes and > suddenly everything works (funnily enough, six slashes also works). > Two slashes and one slash have no effect (no escaping is performed). > > I've got working code so it's not a huge problem, but my curiosity is > piqued. What's going on here that I don't understand? irb(main):009:0> a='\\\\1' => "\\\\1" irb(main):010:0> a.size => 3 irb(main):011:0> a='\\\\\1' => "\\\\\\1" irb(main):012:0> a.size => 4 irb(main):013:0> a='\\\\\\1' => "\\\\\\1" irb(main):014:0> a.size => 4 In a single-quoted string: \' => ' \\ => \ \x => \x for all other x So '...\1' and '...\\1' are identical. HTH, Brian.