From: Robert Klemme Date: 2012-09-01T21:00:57+09:00 Subject: Re: Can someone explain this regex issue to me? I don't see immediate answers to this in the ML but others might still have answered it already. On Fri, Aug 31, 2012 at 5:50 PM, Luke Pearce wrote: > Using 1.9.3p194: > >> puts "\+" > + > >> puts "\\+" > \+ > >> puts "\\" > \ > > However not what I'd expect (1): > >> puts "hi + bye".gsub(/\+/, "\\+") > hi bye > > This gives the expected output: > >> puts "hi + bye".gsub(/\+/, "\\\\+") > hi \+ bye > > I can understand why I need to double escape the + to get \+ in the > output but shouldn't (1) above at least print "hi + bye"? There are two levels of escapes and it happens that the backslash is the escape character for _both levels_: 1. string (i.e. what makes "\n" create a string with the line terminator) 2. regular expression replacement pattern (e.g. \1 as a backreference) If you want to have a literal backslash in the result, you need to escape it, i.e. you need this in the replacement string \\ To get that, you need to escape each backslash so string escaping does not eat it, so you do "\\\\" irb(main):005:0> puts "\\" \ => nil irb(main):006:0> puts "\\\\" \\ => nil Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/