How to use regexp to replace character with backslash plus t

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?

have a nice day
bye

Maciej P. wrote:

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:

;!&%$

On Sat, 18 Nov 2006 10:02:59 -0800, Paul L. [email protected]
wrote:

data.gsub!(%r{([;!&%$’ ])},‘\\\1’)

Thank you. But what is the interpretation of 5! backshlashes. First
two to achieve one textual backslash – the last one, to get the
on-fly variable. And the rest two?

have a nice day
bye

On 18 Nov 2006 10:47:44 -0800, “Phrogz” [email protected] wrote:

Please search the mailing list archive - this question comes up at
least once a month.

Thank you, but as you can see – google – not in that context – so
often. I found ‘answer’ at RubyCentral, but I am still not convinced
it works properly. Why
\ \1
is ok, but
\\1
not? If there is some kind of two-pass parsing – as RubyCentral
explains
\ \1
should be converted to
\1
or even
1
but it is not.

It looks like some too greedy substitution/parsing algorithm – I mean
at first the two first backshlashes are grouped together, then the
second and the third.

have a nice day
bye

Maciej P. wrote:

Thank you. But what is the interpretation of 5! backshlashes. First
two to achieve one textual backslash – the last one, to get the
on-fly variable. And the rest two?

Please search the mailing list archive - this question comes up at
least once a month.

Try this:
http://groups.google.com/group/comp.lang.ruby/search?group=comp.lang.ruby&q=backslash&qt_g=1

Paul L. wrote:

return filename.gsub(/([;!&%$’ ])/,’\\1’)
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 }” }
;!&%$

William J. wrote:

/ …

;!&%$
Yes, except that I hate using those Perlish globals. Just a personal
thing.