如何使用 Ruby 转义 Unicode 字符串? [英] How do I escape a Unicode string with Ruby?

查看:90
本文介绍了如何使用 Ruby 转义 Unicode 字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用反斜杠将 Unicode 字符串编码/转换为其转义形式.有人知道怎么做吗?

I need to encode/convert a Unicode string to its escaped form, with backslashes. Anybody know how?

推荐答案

在 Ruby 1.8.x 中,String#inspect 可能就是你要找的,例如

In Ruby 1.8.x, String#inspect may be what you are looking for, e.g.

>> multi_byte_str = "hello\330\271!"
=> "hello\330\271!"

>> multi_byte_str.inspect
=> "\"hello\\330\\271!\""

>> puts multi_byte_str.inspect
"hello\330\271!"
=> nil

在 Ruby 1.9 中,如果您希望多字节字符的组件字节被转义,您可能想说:

In Ruby 1.9 if you want multi-byte characters to have their component bytes escaped, you might want to say something like:

>> multi_byte_str.bytes.to_a.map(&:chr).join.inspect
=> "\"hello\\xD8\\xB9!\""

在 Ruby 1.8 和 1.9 中,如果您对(转义的)unicode 代码点感兴趣,您可以这样做(尽管它也转义了可打印的内容):

In both Ruby 1.8 and 1.9 if you are instead interested in the (escaped) unicode code points, you could do this (though it escapes printable stuff too):

>> multi_byte_str.unpack('U*').map{ |i| "\\u" + i.to_s(16).rjust(4, '0') }.join
=> "\\u0068\\u0065\\u006c\\u006c\\u006f\\u0639\\u0021"

这篇关于如何使用 Ruby 转义 Unicode 字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆