dqwmhrxt68679 2019-04-10 18:21
浏览 759
已采纳

在Go中将带有UTF-8字节字符串的命令行输出转换为Unicode代码点

I am running an executable from Go via os.Exec, which gives me the following output: (\\xe2\\x96\\xb2). The output contains a UTF-8 byte string, which I want to convert to the corresponding Unicode codepoint (U+25B2). What I am expecting to see, or trying to convert to is: "(▲)". I have looked at this entry in the Go Blog (https://blog.golang.org/strings), but it starts out with an Interpreted string literal, whereas the command output seems to be a Raw string literal. I have tried strconv.Quote and strconv.Unquote, which does not achieve what I'm looking for.

  • 写回答

1条回答 默认 最新

  • douyong4623 2019-04-10 21:30
    关注

    You can use the strconv package to parse the string literal containing the escape sequences.

    The quick and dirty way is to simply add the missing quotes and interpret it as a quoted string using strconv.Unquote

    s := `\xe2\x96\xb2`
    s, err := strconv.Unquote(`"` + s + `"`)
    

    You can also directly parse the string one character at a time (which is what Unquote does internally), using strconv.UnquoteChar

    s := `\xe2\x96\xb2`
    buf := make([]byte, 0, 3*len(s)/2)
    for len(s) > 0 {
        c, _, ss, err := strconv.UnquoteChar(s, 0)
        if err != nil {
            log.Fatal(err)
        }
        s = ss
        buf = append(buf, byte(c))
    }
    s = string(buf)
    

    https://play.golang.org/p/6SDij9d-aRr

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 FOR循环语句显示查询超过300S错误怎么办
  • ¥15 数电设计题 没有设计思路 不知道用什么芯片进行设计 求提供设计思路
  • ¥15 在动态多目标优化问题中,第一幅图展示的是问题DF6的相关定义和绘制的POS和POF图,请问图中公式PS(t)和PF(t)是如何推导的
  • ¥60 先数学建模,接着设计一种优化算法结合案例给出智能仓储四向穿梭车的调度计划
  • ¥15 Errno2:No such file or directory,在当前文件确实没有该图片,怎么解决?
  • ¥15 博世摄像头数据存储的问题(iscsi)
  • ¥15 如何实现对学生籍贯信息管理系统的选择排序
  • ¥15 写一个51单片机的时钟代码
  • ¥15 git clone报错
  • ¥15 3d-slicer超声造影动态图像导入报错