【问题标题】:How to remove 4 byte characters?如何删除 4 字节字符?
【发布时间】:2015-03-22 19:08:28
【问题描述】:

我与 facebook 集成了一个向我发送特殊字符(笑脸等,例如被称为笑脸的 u+1f600)的集成。无法将其存储在我的 UTF8(不是 UTF8mb4)数据库中,那么如何使字符串 UFT8(不是 UTF8mb4)友好?

我无法将我的数据库转换为 UTF8mb4。

【问题讨论】:

    标签: c# .net utf-8 character-encoding character


    【解决方案1】:

    您可以使用简单的正则表达式:

    var rx = new Regex(@"[\uD800-\uDBFF][\uDC00-\uDFFF]");
    string str = "abcd\U0001D11Eabcd";
    str = rx.Replace(str, "?"); // abcd?abcd
    

    如果您查看http://en.wikipedia.org/wiki/UTF-16,您会发现非 BMP 字符由两个 16 位代码单元组成,范围在正则表达式中。

    【讨论】:

    • 我看过一个看起来像这样的示例 .replaceAll("[^\\u0000-\\uFFFF]", "");,看起来它会删除更多的 4 字节字符然后你的例子?还是我错了?你怎么知道你应该只使用 D800-BFF 和 DV00-DFFF?
    • @Banshee On .replaceAll("[^\\u0000-\\uFFFF]", ""):你不能这样做,因为在 .NET 中,非 bmp 字符是 two chars,而正则表达式不知道如何合并它们。所以那个替换不会匹配任何东西。您甚至可以使用我在示例中给出的str 对其进行测试。
    • @Banshee 在D800-BFF and DV00-DFFF 上,它甚至写在响应If you look http://en.wikipedia.org/wiki/UTF-16 you'll see that non-BMP characters are composed by two 16 bit code units, with the ranges given in the Regex. 和wiki 中:The top ten bits (a number in the range 0..0x03FF) are added to 0xD800 to give the first 16-bit code unit or high surrogate, which will be in the range **0xD800..0xDBFF**. 和其他范围在下一行。
    猜你喜欢
    • 1970-01-01
    • 2013-05-05
    • 2012-03-04
    • 2012-01-19
    • 1970-01-01
    • 2013-03-04
    • 2017-07-02
    • 2015-01-11
    • 1970-01-01
    相关资源
    最近更新 更多