I am confused with the following result,
I have a string like this:-
string = "hai\"hello\!tst\`\~end"
When I use space between backslash and back-reference (\1) it is working fine as expected.
puts string.gsub(/([\"\!\`\~])/,'\\ \1')
=> hai\ "hello\ !tst\ `\ ~end
But the same thing is not working without space! The string is replaced with the backreference number.
puts string.gsub(/([\"\!\`\~])/,'\\\1')
=> hai\1hello\1tst\1\1end
But I am expecting answer like
=> hai\"hello\!tst\`\~end
Let me know if you need more information. Thanks in advance.
What you need is more backslashes:
Two-step processing is performed on the secont argument of
gsub, so that\\\1becomes\\1becomes literal\1. With five backslashes first four of them are reduced to one, and\1escape sequence is intact and available for replacing.