如何在lua中将字节编码为utf8?

时间:2017-07-05 12:58:13

标签: lua zlib openresty

由zlib解压缩并打印到日志的字符串格式如下。

 {\x22uid\x22:\x22CE57134D17B57E873D7E7434E0E21783\x22.............2\x5Cu0000\x5Cu0000\x22,\x22http://tgs.7477.com/adiframe/ky/01/index.html\x5Cu0000\x5Cu0000\x22,\x22http://s.csbew.com/acookie.html\x5Cu0000\x5Cu0000\x22],\x22ver\x22:\x221\x22}\x0A200

如何对解压缩的str进行编码,使其显示时不会显示' \ xxx \ u000'在lua?

1 个答案:

答案 0 :(得分:0)

尝试使用此unescape函数从十六进制表示中获取字符:

    function unescape (s)
        s = string.gsub(s or '', "\\x(%x%x)", function (h) return string.char(tonumber(h,16)) end)
        return s
    end


    local str = [[{\x22uid\x22:\x22CE57134D17B57E873D7E7434E0E21783\x22.............2\x5Cu0000\x5Cu0000\x22,\x22http://tgs.7477.com/adiframe/ky/01/index.html\x5Cu0000\x5Cu0000\x22,\x22http://s.csbew.com/acookie.html\x5Cu0000\x5Cu0000\x22],\x22ver\x22:\x221\x22}\x0A200 ]]
    print( unescape(str) )

结果:

 {"uid":"CE57134D17B57E873D7E7434E0E21783".............2\u0000\u0000","http://tgs.7477.com/adiframe/ky/01/index.html\u0000\u0000","http://s.csbew.com/acookie.html\u0000\u0000"],"ver":"1"}
200