4

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?

4

3 回答 3

4

原因是因为两者/都不\是正则表达式中的有效字符。所以他们必须通过\在他们面前放一个来逃脱。如此\成为\\/成为\/。将它们放在另一组斜杠中以构成 Regexp 文字,我们得到:

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

另一种写法是:

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

您应该查看 rubular 以了解开发 Regexp 字符串的好方法。

http://rubular.com/r/ml1a9Egv4B

于 2012-04-01T00:47:42.077 回答
3
str = "word \/ word"
p str.delete('\/') #=>"word  word"
# to get rid of the double spaces:
p str.delete('\/').squeeze(' ') #=>"word word"
于 2012-04-01T07:00:35.440 回答
0

它实际上做了你想要的,但不是因为你认为的原因:

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

注意:你需要 gsub!如果要替换字符串的内容

于 2012-04-01T06:05:38.387 回答