From: mike@... (Mike Stok) Date: 2004-02-01T06:55:02+09:00 Subject: Re: regex bug? In article <20040131052700.GA5270@mulan.thereeds.org>, Mark J. Reed wrote: >On Sat, Jan 31, 2004 at 01:07:42PM +0900, Zach Dennis wrote: >> key = "file" >> attrib = "\\Applications\\4Dapp\\Chess\\" >> command = "xcopy [file] /y /s /e i:\\source\\" >> command.gsub!( /\[#{key}\]/ , "#{attrib}" ) >> puts command >> => "xcopy \\ApplicationsDapp\\Chess\\ /y /s /e i:\\source\\" > >As others have said, '\4' in a gsub string is special. To get around >this you need yet another backslash in front of it, which of course >means two more backslashes between the double quotes: > > attrib = "\\Applications\\\\4Dapp\\Chess\\" > >You can safely double all backslashes in gsub strings, so you might just >want to make it special-processing-proof automatically with some >preparatory munging of your own: > > attrib = "\\Applications\\4Dapp\\Chess\\".gsub(/\\/, '\\\\\\') > >Just as a side note, if you're going to be making literal strings with >backslashes, single quotes cut down on the number of doublings required: > > attrib = '\Applications\4Dapp\Chess\\'.gsub(/\\/, '\\\\\\') also if your replacement includes \ then you might consider using the block form of gsub or gsub! to do the replacement as it doesn't parse the replacement string for you (but does have some overhead): [mike@ratdog mike]$ irb >> key = "file" => "file" >> attrib = "\\Applications\\4Dapp\\Chess\\" => "\\Applications\\4Dapp\\Chess\\" >> command = "xcopy [file] /y /s /e i:\\source\\" => "xcopy [file] /y /s /e i:\\source\\" >> command.gsub!(/\[#{key}\]/) { attrib } => "xcopy \\Applications\\4Dapp\\Chess\\ /y /s /e i:\\source\\" >> puts command xcopy \Applications\4Dapp\Chess\ /y /s /e i:\source\ => nil Hope this helps, Mike -- mike@stok.co.uk | The "`Stok' disclaimers" apply. http://www.stok.co.uk/~mike/ | GPG PGP Key 1024D/059913DA mike@exegenix.com | Fingerprint 0570 71CD 6790 7C28 3D60 http://www.exegenix.com/ | 75D2 9EC4 C1C0 0599 13DA