本文介绍了评估转义的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文件中有一些已经转义的字符串.因此,文件的内容如下所示:

I have some strings in a file that are already escaped. So the content of the file looks like this:

Hello\nWorld. This is\tGreat.

当我读取文件时,我得到的 \ n 是两个不同的字符,而不是一个.

When I read the file, I get \n as two different characters instead of one.

如何将转义的字符串转换为非转义的字符串?

How can I convert an escaped string to a non-escaped one?

推荐答案

基于@deAtog的代码,我做了一些小的补充

based on @deAtog 's code, i made some minor additions

  • 支持\ U00000000格式的字符
  • 在某种程度上简化了十六进制转换

  • support \U00000000 format chars
  • simplify the hex conversions somewhat

string UnEscape(string s)
{
    StringBuilder sb = new StringBuilder();
    Regex r = new Regex("\\\\[abfnrtv?\"'\\\\]|\\\\[0-3]?[0-7]{1,2}|\\\\u[0-9a-fA-F]{4}|\\\\U[0-9a-fA-F]{8}|.");
    MatchCollection mc = r.Matches(s, 0);

    foreach (Match m in mc)
    {
        if (m.Length == 1)
        {
            sb.Append(m.Value);
        }
        else
        {
            if (m.Value[1] >= '0' && m.Value[1] <= '7')
            {
                int i = Convert.ToInt32(m.Value.Substring(1), 8);
                sb.Append((char)i);
            }
            else if (m.Value[1] == 'u')
            {
                int i = Convert.ToInt32(m.Value.Substring(2), 16);
                sb.Append((char)i);
            }
            else if (m.Value[1] == 'U')
            {
                int i = Convert.ToInt32(m.Value.Substring(2), 16);
                sb.Append(char.ConvertFromUtf32(i));
            }
            else
            {
                switch (m.Value[1])
                {
                    case 'a':
                        sb.Append('\a');
                        break;
                    case 'b':
                        sb.Append('\b');
                        break;
                    case 'f':
                        sb.Append('\f');
                        break;
                    case 'n':
                        sb.Append('\n');
                        break;
                    case 'r':
                        sb.Append('\r');
                        break;
                    case 't':
                        sb.Append('\t');
                        break;
                    case 'v':
                        sb.Append('\v');
                        break;
                    default:
                        sb.Append(m.Value[1]);
                        break;
                }
            }
        }
    }

    return sb.ToString();
}

这篇关于评估转义的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 22:41