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

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

概述什么是 Ruby相当于 Python string’s encode('string_escape') and decode functions? 在Python中,我可以执行以下 *** 作: >>> s="this isn't a \"very\" good example!">>> print sthis isn't a "very" good example!>>> s'this isn\ 什么是 Ruby相当于 Python string’s encode('string_escape') and decode functions?

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

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

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

解决方法 大概检查一下

irb(main):001:0> s="this isn't a \"very\" good example!"=> "this isn't a \"very\" good example!"irb(main):002:0> puts sthis isn't a "very" good example!=> nilirb(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!'=> nilirb(main):003:0> puts s.inspect"\" hello\xFF I have\n\r\t\v lots of escapes!'"=> nilirb(main):004:0> puts eval(s.inspect)" hello� I have         lots of escapes!'=> nil

很明显,如果你不是那个进行检查的人,那么不要使用eval,编写自己的/找到一个解析器,但是如果你是在eval之前调用inspect并且s保证是一个字符串,那么它是完全安全的( s.is_a?字符串)

总结

以上是内存溢出为你收集整理的如何在Ruby中安全可逆转义字符串引号?全部内容,希望文章能够帮你解决如何在Ruby中安全可逆地转义字符串引号?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1269172.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)

保存