如何在Ruby中安全可逆地转义字符串引号?

时间:2013-11-14 23:52:52

标签: ruby string encoding

什么是Python string's encode('string_escape') and decode functions的Ruby等价物?

在Python中,我可以执行以下操作:

>>> s="this isn't a \"very\" good example!"
>>> print s
this isn't a "very" good example!
>>> s
'this isn\'t a "very" good example!'
>>> e=s.encode('string_escape')
>>> print e
this isn\'t a "very" good example!
>>> e
'this isn\\\'t a "very" good example!'
>>> d=e.decode('string_escape')
>>> print d
this isn't a "very" good example!
>>> d
'this isn\'t a "very" good example!'

如何在Ruby中执行等效操作?

3 个答案:

答案 0 :(得分:1)

嗯,你可以这样做:

'string"and"something'.gsub '"', '\"'

答案 1 :(得分:0)

可能inspect

irb(main):001:0> s="this isn't a \"very\" good example!"
=> "this isn't a \"very\" good example!"
irb(main):002:0> puts s
this isn't a "very" good example!
=> nil
irb(main):003:0> puts s.inspect
"this isn't a \"very\" good example!"

请注意,解码更加棘手,因为检查也会逃避utf-8文件(如二进制文件)中无效的任何内容,因此如果您知道除了有限的子集之外您将永远不会有任何内容,请使用gsub,但是,只有将它转回字符串的真正方法是从您自己的解析器或eval解析它:

irb(main):001:0> s = "\" hello\xff I have\n\r\t\v lots of escapes!'"
=> "\" hello\xFF I have\n\r\t\v lots of escapes!'"
irb(main):002:0> puts s
" hello� I have

         lots of escapes!'
=> nil
irb(main):003:0> puts s.inspect
"\" hello\xFF I have\n\r\t\v lots of escapes!'"
=> nil
irb(main):004:0> puts eval(s.inspect)
" hello� I have

         lots of escapes!'
=> nil

显然,如果你不是那个inspect的人,那么不要使用eval,编写自己的/找到解析器,但是如果你是那个调用inspect权利的人那么它是完全安全的在eval之前,s保证为字符串(s.is_a? String

答案 2 :(得分:0)

我不知道这是否相关,但如果我想避免处理转义,我只需使用%q[ ]语法

s = %q[this isn't a "very" good example!]
puts s
p s

会给出

'this isn't \ a "very" good example!'
"'this isn't \\ a \"very\" good example!'"