开发者

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"
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜