[英]Remove double backslash from string with Ruby
I have the following string: 我有以下字符串:
string = "\"2014\\/jul\\/grandes\\/volvo-s-60-d5-momentum-1403253_2.jpg\""
that I want to gsub into this string: 我想gsub到这个字符串:
string = "2014/jul/grandes/volvo-s-60-d5-momentum-1403253_2.jpg"
Here is how I thought it should work: 我认为这应该起作用:
string.gsub(/\\./,'')
but this returns: 但这返回:
"\"2014julgrandesvolvo-s-60-d5-momentum-1403253_3.jpg\""
What am I doing wrong? 我究竟做错了什么?
You have a “dot” in regexp for no reason. 您无故在regexp中有一个“点”。 Instead of:
代替:
string.gsub(/\\./,'')
try: 尝试:
string.gsub(/["\\]/,'')
Or, credits to @sawa, try this instead: 或者,将积分计入@sawa,请尝试以下方法:
string.tr('"\\','')
Or, credits to @Chirantan: 或者,归功于@Chirantan:
string.delete('"\\')
Benchmarks: http://gist.github.com/dominikh/208915 基准: http : //gist.github.com/dominikh/208915
string.delete('\\\"')
is one possible solution. 是一种可能的解决方案。 But I'm sure there are better ones out there.
但是我敢肯定那里有更好的。
Another nasty one using String#[]=
method. 使用
String#[]=
方法的另一个讨厌的人 。 This is just for fun :- 这只是为了好玩:-
string[/["\\]/] = '' until string[/["\\]/].nil?
# or
string[/["\\]/] = '' while string =~ /["\\]/
But #gsub
is better way to solve this. 但是
#gsub
是解决此问题的更好方法。 If you don't want to modify the original string , then use String#slice
instead of String#[]=
. 如果您不想修改原始字符串 ,请使用
String#slice
而不是String#[]=
。 That's it. 而已。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.