Escaping \ in regular expressions in Ruby
I was parsing a file and some lines of the file ended with "\". I wanted to use gsub to find and replace it. I tried '\' and /\/ and neither one correctly matched "\".
I ended up getting around it by using a combination of chop and strip but it left me thinking how would I do this if I ever need to ag开发者_运维百科ain?
You need to escape the escape sign as well. So this should work:
/\\/
Passing a string to gsub that will then be compiled to a regex:
"abc\def".gsub("\\", "")
=> "abcdef"
Or just providing the regex directly:
"abc\def".gsub(/\\/, "")
=> "abcdef"
精彩评论