From: William James Date: 2006-11-19T11:25:05+09:00 Subject: Re: How to use regexp to replace character with backslash plus this character Paul Lutus wrote: > Maciej Pilichowski wrote: > > > Hello, > > > > 1.8.5. > > > > I want to 'correct' filenames for unix shell so I want to preceed > > any let's say & with backslash. Here is code translated from my > > original script in Perl -- end of the function > > > > return filename.gsub(/([\;\!\&\%\$\' ])/,'\\\1') > > > > However it doesn't do anything good. If I put space in the middle > > \\ \1 > > > > the replacament is correctly recognized. But I don't want to use > > space in the middle. What's wrong here? > > ------------------------------- > #!/usr/bin/ruby -w > > data = ";!&%$" > > data.gsub!(%r{([;!&%$' ])},'\\\\\1') > > puts data > ------------------------------- > > Output: > > \;\!\&\%\$ irb(main):055:0> puts ";!&%$".gsub( /[;!&%$]/, '\\\\\&' ) \;\!\&\%\$ irb(main):008:0> puts ";!&%$".gsub( /[;!&%$]/ ){ "\\" + $& } \;\!\&\%\$ irb(main):009:0> puts ";!&%$".gsub( /[;!&%$]/ ){ "\\#{ $& }" } \;\!\&\%\$ irb(main):011:0> puts ";!&%$".gsub( /([;!&%$])/ ){ "\\#{ $1 }" } \;\!\&\%\$