24

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?

Patrick McDonald
  • 64,141
  • 14
  • 108
  • 120
Firoso
  • 6,647
  • 10
  • 45
  • 91

3 Answers3

43
System.Text.RegularExpressions.Regex.Unescape(@"\r\n\t\t\t\t\t\t\t\t\tHello world!")

Regex.Unescape method documentation

Pavel Chuchuva
  • 22,633
  • 10
  • 99
  • 115
Diego F.
  • 463
  • 4
  • 3
  • 7
    System.Text.RegularExpressions.Regex.Unescape() – Dragouf Jun 30 '11 at 13:55
  • 15
    Beware that this is `Regex` specific and also escapes strings like `@"\["` into `@"["` which is only desired if we are talking about a regex, not a normal string. – Silvermind May 02 '14 at 11:17
10

Hans's code, improved version.

  1. Made it use StringBuilder - a real performance booster on long strings
  2. 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();
        }
    }
    
Martin
  • 10,738
  • 14
  • 59
  • 67
Fyodor Soikin
  • 78,590
  • 9
  • 125
  • 172
  • FYI the listed function has the wrong name - it is /unescaping/ a string, but is called EscapeStringChars(). – redcalx Jun 25 '12 at 13:27
  • This seems to work better than other answers, but still doesn't support all C# escape sequences: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure#unicode-character-escape-sequences – Gru Apr 12 '20 at 10:30
3

Following methods are same as javascript escape/unescape functions:

Microsoft.JScript.GlobalObject.unescape();

Microsoft.JScript.GlobalObject.escape();
Griwes
  • 8,805
  • 2
  • 43
  • 70
hs.jalilian
  • 103
  • 1
  • 2