【问题标题】:How to handle(decode or remove invalid Unicode code point) string with emoji in golang?如何在golang中使用表情符号处理(解码或删除无效的Unicode代码点)字符串?
【发布时间】:2018-10-18 17:30:29
【问题描述】:

示例字符串:

"\u0410\u043b\u0435\u043a\u0441\u0430\u043d\u0434\u0440\u044b! \n\u0421\u043f\u0430\u0441\u0438\u0431\u043e \ud83d\udcf8 link.ru \u0437\u0430 \n#hashtag  Русское слово, an English word"

没有这个\ud83d\udcf8 我的函数运行良好:

func convertUnicode(text string) string {
    s, err := strconv.Unquote(`"` + text + `"`)
    if err != nil {
        // Error.Printf("can't convert: %s | err: %s\n", text, err)
        return text
    }
    return s
}

我的问题是如何检测包含此类条目的文本?以及如何将其转换为表情符号或如何从文本中删除?谢谢

【问题讨论】:

标签: go unicode emoji


【解决方案1】:

好吧,可能不是那么简单,因为\ud83d\udcf8 都不是有效的代码点,而是在 UTF-16 编码中用于编码 \U0001F4F8 的代理对。现在strconv.Unquote 会给你两个代理的一半,你必须自己组合。

  1. 使用 strconv.Unquote 来取消引用。
  2. 为方便起见,转换为 []rune。
  3. 使用 unicode/utf16.IsSurrogate 查找代理对。
  4. 将代理对与 unicode/utf16.DecodeRune 结合起来。
  5. 转回字符串。

【讨论】:

    猜你喜欢
    • 2012-02-04
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 2020-03-28
    • 2017-10-16
    • 2015-01-18
    相关资源
    最近更新 更多