From: Marnen Laibow-Koser Date: 2010-01-14T00:56:35+09:00 Subject: Re: Ruby Regex Robert Klemme wrote: > 2010/1/13 Brian Candler : >>> irb(main):038: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. :-) ...and Ruby's stupid backslash handling strikes again. This is a completely brain-dead way to do it, and is one of the few things I really hate about Ruby. > > Kind regards > > robert Best, --  Marnen Laibow-Koser http://www.marnen.org marnen@marnen.org -- Posted via http://www.ruby-forum.com/.