How can I Unescape and Reescape strings in .net?

半城伤御伤魂 提交于 2019-12-28 01:28:13

问题


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?


回答1:


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

Regex.Unescape method documentation




回答2:


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();
        }
    }
    



回答3:


Following methods are same as javascript escape/unescape functions:

Microsoft.JScript.GlobalObject.unescape();

Microsoft.JScript.GlobalObject.escape();


来源:https://stackoverflow.com/questions/2661169/how-can-i-unescape-and-reescape-strings-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!