Dan Galipo
Dan Galipo

Reputation: 268

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 again?

Upvotes: 1

Views: 108

Answers (2)

jhickner
jhickner

Reputation: 1053

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"

Upvotes: 1

Gumbo
Gumbo

Reputation: 655269

You need to escape the escape sign as well. So this should work:

/\\/

Upvotes: 3

Related Questions