use*_*123 3 c# unicode replace
我试图从给定的字符串中删除像✅⛱⛄这样的字符.这些字符属于UnicodeCategory.OtherSymbol
,但char.GetUnicodeCategory
返回UnicodeCategory.Surrogate
.
如果我只想从字符串中删除那些情感/图片字符并保持其他代理字符不受影响,我该怎么办?
我试过了Regex.IsMatch("", @"\p{So}")
,没用.
在迭代Unicode字符而不是UTF-16代码单元时,.NET并不是非常好.所有相关的代码都在那里,但它并不是非常容易使用.有可能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();
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
487 次 |
最近记录: |