如何反转义在C#unicode字符串 [英] How to unescape unicode string in C#
问题描述
我有一个文本文件,这样一个Unicode字符串。而我要显示的真正性质
例如:
\\\计\\\算\\\机\\\•\\\网\\\络\\\•\\\技\\\术\\\类
在读取文本文件中这个字符串,用 StreamReader.ReadToLine()
,它逃脱 \
到'\\'
如\\\\计
,其中是不是想要的。
这将显示Unicode字符串相同的文字。这我想是为了显示真实的性格。
- 如何更改
\\\\计
到在结果字符串\\\计
。 - 还是应该使用其他阅读器阅读的字符串?
如果你有一个像
$ B $字符串b
VAR输入1 =\\\计\\\算\\\机\\\•\\\网\\\络\\\•\\\技\\\术\\\类;
//输入1 ==计算机•网络•技术类
你不需要任何取消转义。这只是字符串包含转义序列,而不是字符串本身。
如果你有这样一个字符串
VAR输入2 = @\\\计\\\算\\\机\\\•\\\网\\\络\\\•\ u6280\\\术\\\类;
您可以用下面的正则表达式反转义是:
VAR的结果= Regex.Replace(
输入2,
@\\ [支原体]([0-9A发-F] {4 }),
M = GT; char.ToString(
(炭)ushort.Parse(m.Groups [1] .value的,NumberStyles.AllowHexSpecifier)));
//结果==计算机•网络•技术类
I have a Unicode string from a text file such that. And I want to display the real character.
For example:
\u8ba1\u7b97\u673a\u2022\u7f51\u7edc\u2022\u6280\u672f\u7c7b
When read this string from text file, using StreamReader.ReadToLine()
, it escape the \
to '\\'
such as "\\u8ba1"
, which is not wanted.
It will display the Unicode string same as from text. Which I want is to display the real character.
- How can change the
"\\u8ba1"
to"\u8ba1"
in the result string. - Or should use another Reader to read the string?
If you have a string like
var input1 = "\u8ba1\u7b97\u673a\u2022\u7f51\u7edc\u2022\u6280\u672f\u7c7b";
// input1 == "计算机•网络•技术类"
you don't need to unescape anything. It's just the string literal that contains the escape sequences, not the string itself.
If you have a string like
var input2 = @"\u8ba1\u7b97\u673a\u2022\u7f51\u7edc\u2022\u6280\u672f\u7c7b";
you can unescape it using the following regex:
var result = Regex.Replace(
input2,
@"\\[Uu]([0-9A-Fa-f]{4})",
m => char.ToString(
(char)ushort.Parse(m.Groups[1].Value, NumberStyles.AllowHexSpecifier)));
// result == "计算机•网络•技术类"
这篇关于如何反转义在C#unicode字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!