Jacob Terry
Jacob Terry

Reputation: 209

Regex / Remove slash from string in ruby

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?

Upvotes: 5

Views: 17469

Answers (3)

Grant Hutchins
Grant Hutchins

Reputation: 4409

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

Upvotes: 5

steenslag
steenslag

Reputation: 80065

str = "word \/ word"
p str.delete('\/') #=>"word  word"
# to get rid of the double spaces:
p str.delete('\/').squeeze(' ') #=>"word word"

Upvotes: 3

pguardiario
pguardiario

Reputation: 54984

It actually does what you want but not for the reasons you think:

string = "word \/ word"
# => "word / word"
string.gsub(/\//, "")
# => "word  word"

Note: you need gsub! if you want to replace the contents of string

Upvotes: 0

Related Questions