如何从字符串中删除Unicode.OtherSymbol?

3

我正在尝试从给定字符串中删除像✅⛱⛄这样的字符。这些字符属于UnicodeCategory.OtherSymbol,但是char.GetUnicodeCategory返回UnicodeCategory.Surrogate

如果我只想从字符串中删除这些表情/图片字符,并保留其他代理字符不变,该怎么办?

我已经尝试过 Regex.IsMatch("", @"\p{So}"),但没有起作用。


1
这里展示的三个字符(勾号、雨伞、无雪人)可以使用char.GetUnicodeCategory(char)。另外两个字符由两个char值组成,形成代理对。你需要使用char.GetUnicodeCategory(string, int)来处理它们。 - Jon Skeet
1个回答

6

.NET在迭代Unicode字符而不是UTF-16代码单元方面表现并不好。所有相关的代码都在那里,但使用起来并不是特别容易。可能可以通过Regex使其理解代理对,但我还没有找到它。

以下是手动处理的示例:

using System;
using System.Globalization;
using System.Text;

public class Program
{
    public static void Main(string[] args)
    {
        string text = "a\u2705b\U0001f52ec\u26f1d\U0001F602e\U00010000";
        string cleansed = RemoveOtherSymbols(text);
        Console.WriteLine(cleansed);
    }

    static string RemoveOtherSymbols(string text)
    {
        // TODO: Handle malformed strings (e.g. those
        // with mismatched surrogate pairs)
        StringBuilder builder = new StringBuilder();
        int index = 0;
        while (index < text.Length)
        {
            // Full Unicode character
            int units = char.IsSurrogate(text, index) ? 2 : 1;
            UnicodeCategory category = char.GetUnicodeCategory(text, index);
            int ch = char.ConvertToUtf32(text, index);
            if (category == UnicodeCategory.OtherSymbol)
            {
                Console.WriteLine($"Skipping U+{ch:x} {category}");
            }
            else
            {
                Console.WriteLine($"Keeping U+{ch:x} {category}");
                builder.Append(text, index, units);
            }
            index += units;
        }
        return builder.ToString();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接