[英]how to replace an apostrophe using gsub
I want to replace apostrophe(') in a name with "backslash apostrophe" (\\') . 我想用“反斜杠撇号”(\\')替换名称中的撇号(')。 But Unfortunately not getting such a simple thing. 但是不幸的是没有得到这么简单的东西。
So on irb I tried following 所以在irb上,我尝试了以下
x = "stack's" x.gsub(/[\\']/,"\\'") x =“ stack's” x.gsub(/ [\\'] /,“ \\'”)
Some how it is not working I am getting same result- stack's in place of stack\\'s 一些如何不起作用我得到相同的结果-堆栈的位置
尝试这个:
x = "anupam's"; puts x.gsub("'", "\\\\'")
Try this out: 试试看:
x.gsub(/[']/,"\\\\\'")
Result: 结果:
1.9.3p0 :014 > puts x.gsub(/[']/,"\\\\\'")
anupam\'s
Here's a ruby variant for PHPs addslashes method (from http://www.ruby-forum.com/topic/113067#263640 ). 这是PHP的addslashes方法的红宝石变体(来自http://www.ruby-forum.com/topic/113067#263640 )。 This method also escapes \\
in the string, with double \\
: 这种方法也逃脱\\
在字符串中,双\\
:
class String
def addslashes
self.gsub(/['"\\\x0]/,'\\\\\0')
end
end
Which would correctly escape anupam's: 哪个可以正确摆脱anupam的:
"anupam's".addslashes # => "anupam\\'s"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.