Can I convert a C# string value to an escaped string literal

后端 未结 16 1020
时光取名叫无心
时光取名叫无心 2020-11-22 07:51

In C#, can I convert a string value to a string literal, the way I would see it in code? I would like to replace tabs, newlines, etc. with their escape sequences.

If

16条回答
  •  不要未来只要你来
    2020-11-22 07:58

    public static class StringHelpers
    {
        private static Dictionary escapeMapping = new Dictionary()
        {
            {"\"", @"\\\"""},
            {"\\\\", @"\\"},
            {"\a", @"\a"},
            {"\b", @"\b"},
            {"\f", @"\f"},
            {"\n", @"\n"},
            {"\r", @"\r"},
            {"\t", @"\t"},
            {"\v", @"\v"},
            {"\0", @"\0"},
        };
    
        private static Regex escapeRegex = new Regex(string.Join("|", escapeMapping.Keys.ToArray()));
    
        public static string Escape(this string s)
        {
            return escapeRegex.Replace(s, EscapeMatchEval);
        }
    
        private static string EscapeMatchEval(Match m)
        {
            if (escapeMapping.ContainsKey(m.Value))
            {
                return escapeMapping[m.Value];
            }
            return escapeMapping[Regex.Escape(m.Value)];
        }
    }
    

提交回复
热议问题