Regex / Remove slash from string in ruby

Jacob Terry picture Jacob Terry · Apr 1, 2012 · Viewed 14.5k times · Source

Thanks in advance...

I am having some trouble with regular expressions in ruby, or otherwise finding a way to remove a slash from a string. Here is how my string looks:

string = "word \/ word"

I am trying to remove both the backslash and the slash; I want this result:

string = "word  word"

I think I am missing something with escape characters, or who knows what!

I have tried this:

string.gsub(/\//, "")

which will remove the backslash, but leaves the slash. I have tried variations with escape characters all over and in places that don't even make sense!

I am terrible with regex and get very frustrated working with strings in general, and I am just at a loss. I'm sure it's something obvious, but what am I missing?

Answer

Grant Hutchins picture Grant Hutchins · Apr 1, 2012

The reason why is because both / and \ are not valid characters in a Regexp on their own. So they must be escaped by putting a \ before them. So \ becomes \\ and / become \/. Putting these together inside another set of slashes to make a Regexp literal, we get:

string.gsub(/\\\//, "")

Another way to write this is:

string.gsub(/#{Regexp.escape('\/')}/, "")

You should check out rubular for a nice way to develop Regexp strings.

http://rubular.com/r/ml1a9Egv4B