Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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 can 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");
like image 977
Chris Wenham Avatar asked Oct 14 '25 15:10

Chris Wenham


1 Answers

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.

like image 80
João Angelo Avatar answered Oct 17 '25 06:10

João Angelo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!