From: Dave Thomas Date: 2001-01-31T06:09:43+09:00 Subject: [ruby-talk:10140] Re: Easy regex question Neil Conway writes: > In Ruby (Jan 18 snapshot), I get this: > > $ irb > irb(main):001:0> str = "it's me" > "it's me" > irb(main):002:0> str.gsub(/'/, "\\'") > "its mes me" > > Can someone tell me: > > 1) What Ruby is doing? I can't figure out what it's doing to go from > "it's me" -> "its mes me" This is ugly, so brace yourself... "\\'" is a normal string, so before being passed to gsub it undergoes the normal string replacements (things like \n becomes newline, and \\ becomes a single backslash). So what gsub gets passed as a second parameter is the two character string \' Now... Regexp substitution parameters have a number of special purpose escape sequences. \1 matches the first parenthesized subexpression, \& is the whole match, and (wait for it) \' is everything _after_ the match. So, in your case, you've got it<'>s me so everything after the match is 's me', so the string becomes 'its mes me'. > 2) The correct regex to do what I'm looking for Well, there are several options str = "it's me" str.gsub(/'/, "\\\\'") str.gsub(/'/) { "\\'" } Regards Dave