I need a TextBox on a WPF control that can take in text like Commit\r\n\r
(which is the .net string "Commit\\r\\n\\r"
) and convert it back to "Commit\r\n\r"
as a .net string. I was hoping for a string.Unescape() and string.Escape() method pair, but it doesn't seem to exist. Am I going to have to write my own? or is there a more simple way to do this?
Unescape method on the string literal "\\n." This is an escaped backslash "\\" and an "n." Unescape The Unescape method transforms the escaped backslash into a regular backslash "\." Then The method transforms the escaped newline sequence (the two characters "\n") into a real newline.
Converts any escaped characters in the input string.
System.Text.RegularExpressions.Regex.Unescape(@"\r\n\t\t\t\t\t\t\t\t\tHello world!")
Regex.Unescape method documentation
Hans's code, improved version.
Made it an extension method
public static class StringUnescape
{
public static string Unescape(this string txt)
{
if (string.IsNullOrEmpty(txt)) { return txt; }
StringBuilder retval = new StringBuilder(txt.Length);
for (int ix = 0; ix < txt.Length; )
{
int jx = txt.IndexOf('\\', ix);
if (jx < 0 || jx == txt.Length - 1) jx = txt.Length;
retval.Append(txt, ix, jx - ix);
if (jx >= txt.Length) break;
switch (txt[jx + 1])
{
case 'n': retval.Append('\n'); break; // Line feed
case 'r': retval.Append('\r'); break; // Carriage return
case 't': retval.Append('\t'); break; // Tab
case '\\': retval.Append('\\'); break; // Don't escape
default: // Unrecognized, copy as-is
retval.Append('\\').Append(txt[jx + 1]); break;
}
ix = jx + 2;
}
return retval.ToString();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With