[英]How to remove the unicode character in the string
假设我们有一个像下面这样的字符串。
string s = "此检查项己被你忽略,请联系医生。\u2028内科";
如何删除字符串中像\
这样的 unicode 字符?
我试过下面的功能。 不幸的是,它们都不起作用。 请救救我。 谢谢。
更新
为什么下面的代码对我不起作用?
更新我试图在输出中显示字符串。 它是一个行分隔符。
正如@spender 在上面的评论中所指出的:
您的问题(删除 unicode)的基本前提已被破坏,因为所有字符串都以 unicode 形式存储在内存中。 所有字符都是Unicode。
但是,如果您想替换/删除格式为"\\uXXXX"
的非转义字符串,则可以使用类似以下正则表达式模式的内容: @"\\\\u[0-9A-Fa-f]{4}"
这是一个完整的例子:
string noUnicode = "此检查项己被你忽略,请联系医生。内科";
// If you hard-code the string, you MUST add an `@` before the string, otherwise,
// the "u2028" will get escaped and converted to its corresponding Unicode character.
string s = @"此检查项己被你忽略,请联系医生。\u2028内科";
string ss = Regex.Replace(s, @"\\u[0-9A-Fa-f]{4}", string.Empty);
Debug.Print("s = " + s);
Debug.Print("ss = " + ss);
Debug.Print((ss == noUnicode).ToString());
注意:由于字符串是硬编码的,所以这里必须使用@
,以防止子字符串"\
"
被转换为对应的Unicode字符。 另一方面,如果您从其他地方获取原始字符串(例如,从文本文件中读取),则子字符串"\
"
已经按原样表示,应该没有问题,上面的代码应该可以工作正好。
所以,像这样的事情会完全一样:
string s = File.ReadAllText(@"Path\to\a\Unicode\text\file\containing\the\string\'\u2028'");
string ss = Regex.Replace(s, @"\\u[0-9A-Fa-f]{4}", string.Empty);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.