From: Mike Stok Date: 2001-01-31T06:01:50+09:00 Subject: [ruby-talk:10139] Re: Easy regex question On Wed, 31 Jan 2001, Neil Conway wrote: > Hi all, > > I just learned Ruby recently (coming from Perl/Java/Python), and I've got > a simple question about regular expressions that I just can't seem to > work out. I'm trying to SQL quote a string (for now, just replacing all > single-quotes with backslash-single-quote - i.e. ' -> \'). > > In Perl, the following works fine: > > $ perl > $str = "it's me"; > $str =~ s/'/\\'/g; > print "$str\n"; > it\'s me [...] > Can someone tell me: > > 2) The correct regex to do what I'm looking for str.gsub(/'/, "\\\\'") or str.gsub(/'/) {"\\'"} seem to work: irb(main):008:0> puts str.gsub(/'/, "\\\\'") it\'s me nil irb(main):009:0> puts str.gsub(/'/) {"\\'"} it\'s me nil This is because the \\\\ gets turned into \\ as the program gets read in, and the \\ gets turned into \ by the regex engine. If you can find Programming Ruby in a book store then page 64 has a description of this. Hope this helps, Mike -- mike@stok.co.uk | The "`Stok' disclaimers" apply. http://www.stok.co.uk/~mike/ | GPG PGP Key 1024D/059913DA | Fingerprint 0570 71CD 6790 7C28 3D60 stok@colltech.com (CT - work) | 75D2 9EC4 C1C0 0599 13DA