开发者

Escaping \ in regular expressions in Ruby

开发者 https://www.devze.com 2022-12-14 03:10 出处:网络
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 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"
0

精彩评论

暂无评论...
验证码 换一张
取 消