简体   繁体   English

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

[英]How to safely and reversibly escape string quotes in Ruby?

What is the Ruby equivalent of Python string's encode('string_escape') and decode functions ? 什么是Python字符串的encode('string_escape')decode函数的Ruby等价物?

In Python, I can do the following: 在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!'

How to do the equivalent in Ruby? 如何在Ruby中执行等效操作?

好吧,你可以这样做:

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

Probably inspect 大概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!"

note that decoding is much trickier, as inspect also escapes anything not valid in utf-8 files (like binary), so if you know that you will never have anything aside from a limited subset, use gsub, however, the only real way to turn it back into a string is parsing it, either from your own parser or eval : 请注意,解码更加棘手,因为检查也会逃避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

obviously, if you are not the one doing the inspect , then don't use eval, write your own/find a parser, however its perfectly safe if you are the one calling inspect right before eval and s is guaranteed to be a string ( s.is_a? String ) 很明显,如果你不是那个进行inspect ,那么不要使用eval,编写自己的/找到一个解析器,但是如果你是在eval之前调用inspect并且s保证是一个字符串,那么它是完全安全的( s.is_a? String

I don't know if this is relevant but if I wanted to avoid dealing with escaping I just use %q[ ] syntax 我不知道这是否相关,但如果我想避免处理转义,我只使用%q[ ]语法

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

Will give 会给

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM