From: Robert Klemme Date: 2010-01-13T23:02:23+09:00 Subject: Re: Ruby Regex 2010/1/13 Brian Candler : > Sriram Varahan wrote: >> Hello, >> >> I have a string as a = "&0&1" >> >> I need to pass this value with the ampersand escaped to another command >> in my program. >> >> So I tried something like this: >> >> irb(main):038:0> a.gsub(/&/,"\\&") >> => "&0&1" > > That's because \& has a special meaning in a replacement string ("the > matched string"). Either use a block to provide the replacement value > (which doesn't do the backslash replacement), or put two backslashes in > the replacement string. > > irb(main):002:0> a.gsub(/&/) { "\\&" } > => "\\&0\\&1" > irb(main):003:0> a.gsub(/&/, "\\\\&") > => "\\&0\\&1" But it's only special when preceded by a backslash, which is special in replacement strings. irb(main):002:0> "123".gsub(/\d/, '<&>') => "<&><&><&>" irb(main):003:0> "123".gsub(/\d/, '<\\&>') => "<1><2><3>" irb(main):004:0> "123".gsub(/\d/, '<\\\\&>') => "<\\&><\\&><\\&>" Another example - backslash with group index: irb(main):011:0> "abc".gsub(/\w(.)\w/, '<1>') => "<1>" irb(main):012:0> "abc".gsub(/\w(.)\w/, '<\\1>') => "" irb(main):013:0> "abc".gsub(/\w(.)\w/, '<\\\\1>') => "<\\1>" So what you basically do here is you escape the escape so it looses its special meaning in the replacement string. :-) Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/