23

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
  • 62,076
  • 14
  • 100
  • 117
Firoso
  • 6,467
  • 10
  • 43
  • 91

3 Answers3

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

Regex.Unescape method documentation

Pavel Chuchuva
  • 21,996
  • 9
  • 95
  • 113
Diego F.
  • 453
  • 4
  • 3
  • 7
    System.Text.RegularExpressions.Regex.Unescape() – Dragouf Jun 30 '11 at 13:55
  • 13
    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,308
  • 13
  • 57
  • 67
Fyodor Soikin
  • 74,930
  • 8
  • 118
  • 160
  • 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://docs.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,533
  • 2
  • 42
  • 70
hs.jalilian
  • 105
  • 1
  • 2