How can I Unescape and Reescape strings in .net?

后端 未结 3 574
野的像风
野的像风 2020-11-29 11:03

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 ba

相关标签:
3条回答
  • 2020-11-29 11:36
    System.Text.RegularExpressions.Regex.Unescape(@"\r\n\t\t\t\t\t\t\t\t\tHello world!")
    

    Regex.Unescape method documentation

    0 讨论(0)
  • 2020-11-29 11:41

    Following methods are same as javascript escape/unescape functions:

    Microsoft.JScript.GlobalObject.unescape();
    
    Microsoft.JScript.GlobalObject.escape();
    
    0 讨论(0)
  • 2020-11-29 11:43

    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();
          }
      }
      
    0 讨论(0)
提交回复
热议问题