How to replace "(" to "\(" in Ruby?


#1

I want to change filename “001(abc).gif” to “001(abc).gif”, ie. add “” before “(” and “)”, how to do it?

I try as below, but get wrong output.

            filename.gsub!(/\)/, "\\\)")

#2

Understand that you want to put double quotes before and after parentheses


#3

Not sure how this reads for you. I understand that the goal is to change 123(abc).gif to 123\(abc\).gif, escaping the backslashes. This is a tricky one, as:

if you do you get
.gsub(/([()])/, '\1') 123(abc).gif
.gsub(/([()])/, '\\1') 123(abc).gif
.gsub(/([()])/, '\\\1') 123\1abc\1.gif
.gsub(/([()])/, '\\\\1') 123\1abc\1.gif
.gsub(/([()])/, '\\\\\1') 123\(abc\).gif <- wanted solution

Backslash escaping can be tricky. I don’t know of any good source that explains this in detail. Links welcome!
Rule of thumb: escape \ twice, since the first one means ‘enter backreference mode’ and the second means ‘a literal blackslash character’: so two backslashes (\\) followed by one backreference (\1) is ambiguous, hence the doubling.