dongliushui2001 2018-10-18 17:30
浏览 925
已采纳

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

Example string:

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

Without this \ud83d\udcf8 my func works well:

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

My question is how to detect that text contains this kind of entries? And how to convert it to emoji or how to remove from the text? Thanks

  • 写回答

1条回答 默认 最新

  • dsadsadsa1231 2018-10-18 20:44
    关注

    Well, probably not so simple as neither \ud83d nor \udcf8 are valid code points but together are a surrogate pair used in UTF-16 encoding to encode \U0001F4F8. Now strconv.Unquote will give you two surrogate halves which you have to combine yourself.

    1. Use strconv.Unquote to unquote as you did.
    2. Convert to []rune for convenience.
    3. Find surrogate pairs with unicode/utf16.IsSurrogate.
    4. Combine surrogate pairs with unicode/utf16.DecodeRune.
    5. Convert back to string.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题