开发者

Interpolating special characters (\t, \n, \r etc.) at runtime in C#

开发者 https://www.devze.com 2022-12-24 07:50 出处:网络
The C# compiler interpolates special character literals like \\t for tab, \\n for newline etc. But is there a built-in C# or .Net function that can interpolate them at runtime?

The C# compiler interpolates special character literals like \t for tab, \n for newline etc. But is there a built-in C# or .Net function that can interpolate them at runtime?

For example, at runtime I read a configuration for a text-delimited file format, maybe something like this:

Delimiter: \t
LineEnding: \r\n

Right now the only thing I c开发者_运维百科an think of doing is reading in the string and then performing a Replace() with compiler-interpolated strings:

Delimiter = Delimiter.Replace(@"\n", "\n").Replace(@"\r", "\r");


You can try Regex.Unescape which possible satisfies all your requirements.

foreach (var special in new string[] { @"\n", @"\t", @"\r\n" })
{
    Console.WriteLine("|{0}|", special);
    Console.WriteLine("|{0}|", Regex.Unescape(special));
    Console.WriteLine("----------------------"); 
}

From MSDN:

It replaces the representation of unprintable characters with the characters themselves. For example, it replaces \a with \x07. The character representations it replaces are \a, \b, \e, \n, \r, \f, \t, and \v.

0

精彩评论

暂无评论...
验证码 换一张
取 消