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!(/\)/, "\\\)")
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!(/\)/, "\\\)")
Understand that you want to put double quotes before and after parentheses
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.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs