如何在 golang 中处理(解码或删除无效的 Unicode 代码点)带有表情符号的字符串?

How to handle(decode or remove invalid Unicode code point) string with emoji in golang?

示例字符串:

"\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
}

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

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

  1. 像您一样使用 strconv.Unquote 取消引用。
  2. 为方便起见转换为 []符文。
  3. 使用 unicode/utf16.IsSurrogate.
  4. 查找代理对
  5. 将代理对与 unicode/utf16.DecodeRune.
  6. 组合
  7. 转换回字符串。