ruby 用反斜杠单引号替换单引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10551982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace single quote with backslash single quote
提问by bobomoreno
I have a very large string that needs to escape all the single quotes in it, so I can feed it to JavaScript without upsetting it. I have no control over the external string, so I can't change the source data.
我有一个非常大的字符串,需要对其中的所有单引号进行转义,因此我可以将它提供给 JavaScript 而不会打扰它。我无法控制外部字符串,因此无法更改源数据。
Example:
例子:
Cote d'Ivtheitroad -> Cote d\'Ivtheitroad
(the actual string is very long and contains many single quotes)
(实际字符串很长,包含很多单引号)
I'm trying to this by using gsubon the string, but can't get this to work:
我正在尝试通过gsub在字符串上使用来实现这一点,但无法使其正常工作:
a = "Cote d'Ivtheitroad"
a.gsub("'", "\\'")
but this gives me:
但这给了我:
=> "Cote dIvtheitroadIvtheitroad"
I also tried:
我也试过:
a.gsub("'", 92.chr + 39.chr)
but got the same result; I know it's something to do with regular expressions, but I never get those.
但得到了相同的结果;我知道这与正则表达式有关,但我从来没有得到这些。
回答by steenslag
The %q delimiters come in handy here:
%q 分隔符在这里派上用场:
# %q(a string) is equivalent to a single-quoted string
puts "Cote d'Ivtheitroad".gsub("'", %q(\\')) #=> Cote d\'Ivtheitroad
回答by Chowlett
The problem is that \'in a gsubreplacement means "part of the string after the match".
问题是\'在gsub替换中意味着“匹配后的字符串的一部分”。
You're probably best to use either the block syntax:
您可能最好使用块语法:
a = "Cote d'Ivtheitroad"
a.gsub(/'/) {|s| "\'"}
# => "Cote d\'Ivtheitroad"
or the Hash syntax:
或哈希语法:
a.gsub(/'/, {"'" => "\'"})
There's also the hacky workaround:
还有一个hacky解决方法:
a.gsub(/'/, '\#').gsub(/#/, "'")
回答by kukrt
# prepare a text file containing [ abcd\'efg ]
require "pathname"
backslashed_text = Pathname("/path/to/the/text/file.txt").readlines.first.strip
# puts backslashed_text => abcd\'efg
unslashed_text = "abcd'efg"
unslashed_text.gsub("'", Regexp.escape(%q|\'|)) == backslashed_text # true
# puts unslashed_text.gsub("'", Regexp.escape(%q|\'|)) => abcd\'efg

