用反斜杠单引号替换单引号

时间:2012-05-11 13:07:50

标签: ruby string

我有一个非常大的字符串需要转义其中的所有单引号,所以我可以将它提供给JavaScript而不会让它失望。 我无法控制外部字符串,因此无法更改源数据。

示例:

Cote d'Ivoir  -> Cote d\'Ivoir  

(实际字符串很长,包含许多单引号)

我正在尝试通过在字符串上使用gsub,但无法使其工作:

a = "Cote d'Ivoir"
a.gsub("'", "\\\'")

但是这给了我:

=> "Cote dIvoirIvoir"

我也尝试过:

a.gsub("'", 92.chr + 39.chr)

但得到了同样的结果;我知道这与正则表达式有关,但我从来没有得到那些。

3 个答案:

答案 0 :(得分:56)

%q分隔符在这里派上用场:

# %q(a string) is equivalent to a single-quoted string
puts "Cote d'Ivoir".gsub("'", %q(\\\')) #=> Cote d\'Ivoir

答案 1 :(得分:19)

问题是\'替换中的gsub表示“匹配后字符串的一部分”。

您最好使用块语法:

a = "Cote d'Ivoir"
a.gsub(/'/) {|s| "\\'"}
# => "Cote d\\'Ivoir"

或哈希语法:

a.gsub(/'/, {"'" => "\\'"})

还有hacky解决方法:

a.gsub(/'/, '\#').gsub(/#/, "'")

答案 2 :(得分:0)

# 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