From: Jon Garvin Date: 2009-02-11T03:26:41+09:00 Subject: Re: regex to escape special characters --------------030705080808070308030802 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 7bit Tim Hunter wrote: > Jon Garvin wrote: > >> I've got the following string... >> >> "This is ( a test" >> >> And I want to do a regex gsub on it to turn it into... >> >> "This is \( a test" >> >> In irb, If I start with... >> >> "This is ( a test".gsub(/[\(]/,'\&') => "This is ( a test" >> >> And then progressively added more backslashes, I get the following >> results, none of which are what I'm looking for. The second one is, >> IMO, the one that should work. >> >> "This is ( a test".gsub(/[\(]/,'\\&') => "This is ( a test" >> "This is ( a test".gsub(/[\(]/,'\\\&') => "This is \\& a test" >> "This is ( a test".gsub(/[\(]/,'\\\\&') => "This is \\& a test" >> "This is ( a test".gsub(/[\(]/,'\\\\\&')=> "This is \\( a test" >> >> >> Am I just having a serious case of the mondays, or is there a bug in how >> Ruby deals with \ characters when trying to represent an actual single \ >> character? >> >> I'm using ruby 1.8.6 (2007-09-24 patchlevel 111) [i486-linux] >> > > irb shows you the result using p, which escapes special characters in > the string it displays. Use puts to see the actual string. > > C:\>irb > irb(main):001:0> x = "This is ( a test" > => "This is ( a test" > irb(main):002:0> x.gsub(/\(/, '\\\(') > => "This is \\( a test" > irb(main):003:0> y = x.gsub(/\(/, '\\\(') > => "This is \\( a test" > irb(main):004:0> puts y > This is \( a test > => nil > irb(main):005:0> > Oh, fer cryin' out loud. Case of the mondays it is. Thanks. -- http://www.5valleys.com/ http://www.workingwithrails.com/person/8078 --------------030705080808070308030802--