【C# 变量字符串还原转义字符】

在 C# 中,如果字符串中包含转义字符(如 \n\t\x001E 等),并且你希望将这些转义字符还原为它们实际表示的字符或字符串,可以使用以下方法:


1. 使用 Regex.Unescape 方法

Regex.Unescape 方法可以将字符串中的转义字符还原为实际字符。例如,将 \n 还原为换行符,将 \x001E 还原为对应的 Unicode 字符。

示例代码:
csharp 复制代码
using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string input = @"Hello\x001EWorld\n\tTest";
        string unescapedString = Regex.Unescape(input);

        Console.WriteLine(unescapedString); // 输出: HelloWorld
                                           //        Test
    }
}
说明:
  • \x001E 被还原为 Unicode 字符 (记录分隔符)。
  • \n 被还原为换行符。
  • \t 被还原为制表符。

2. 手动处理转义字符

如果需要手动处理特定的转义字符,可以使用 switchif 语句逐个替换。

示例代码:
csharp 复制代码
using System;
using System.Text;

class Program
{
    static void Main()
    {
        string input = @"Hello\x001EWorld\n\tTest";
        string unescapedString = UnescapeString(input);

        Console.WriteLine(unescapedString); // 输出: HelloWorld
                                           //        Test
    }

    static string UnescapeString(string input)
    {
        StringBuilder result = new StringBuilder();
        int i = 0;
        while (i < input.Length)
        {
            if (input[i] == '\\' && i + 1 < input.Length)
            {
                switch (input[i + 1])
                {
                    case 'n':
                        result.Append('\n'); // 换行符
                        i += 2;
                        break;
                    case 't':
                        result.Append('\t'); // 制表符
                        i += 2;
                        break;
                    case 'x':
                        // 处理 \xHH 格式的十六进制转义字符
                        if (i + 4 <= input.Length)
                        {
                            string hexValue = input.Substring(i + 2, 2);
                            int charCode = Convert.ToInt32(hexValue, 16);
                            result.Append((char)charCode);
                            i += 4;
                        }
                        else
                        {
                            result.Append(input[i]);
                            i++;
                        }
                        break;
                    default:
                        result.Append(input[i]);
                        i++;
                        break;
                }
            }
            else
            {
                result.Append(input[i]);
                i++;
            }
        }
        return result.ToString();
    }
}

3. 处理 Unicode 转义字符

如果需要处理 \uHHHH 格式的 Unicode 转义字符,可以扩展上述方法。

示例代码:
csharp 复制代码
using System;
using System.Text;

class Program
{
    static void Main()
    {
        string input = @"Hello\u001EWorld\n\tTest";
        string unescapedString = UnescapeString(input);

        Console.WriteLine(unescapedString); // 输出: HelloWorld
                                           //        Test
    }

    static string UnescapeString(string input)
    {
        StringBuilder result = new StringBuilder();
        int i = 0;
        while (i < input.Length)
        {
            if (input[i] == '\\' && i + 1 < input.Length)
            {
                switch (input[i + 1])
                {
                    case 'n':
                        result.Append('\n'); // 换行符
                        i += 2;
                        break;
                    case 't':
                        result.Append('\t'); // 制表符
                        i += 2;
                        break;
                    case 'u':
                        // 处理 \uHHHH 格式的 Unicode 转义字符
                        if (i + 6 <= input.Length)
                        {
                            string hexValue = input.Substring(i + 2, 4);
                            int charCode = Convert.ToInt32(hexValue, 16);
                            result.Append((char)charCode);
                            i += 6;
                        }
                        else
                        {
                            result.Append(input[i]);
                            i++;
                        }
                        break;
                    case 'x':
                        // 处理 \xHH 格式的十六进制转义字符
                        if (i + 4 <= input.Length)
                        {
                            string hexValue = input.Substring(i + 2, 2);
                            int charCode = Convert.ToInt32(hexValue, 16);
                            result.Append((char)charCode);
                            i += 4;
                        }
                        else
                        {
                            result.Append(input[i]);
                            i++;
                        }
                        break;
                    default:
                        result.Append(input[i]);
                        i++;
                        break;
                }
            }
            else
            {
                result.Append(input[i]);
                i++;
            }
        }
        return result.ToString();
    }
}

4. 处理代理对(Surrogate Pair)

对于某些 Unicode 字符(如表情符号),它们可能由两个 char 值(称为代理对)表示。可以使用 char.ConvertToUtf32char.ConvertFromUtf32 来处理。

示例代码:
csharp 复制代码
using System;
using System.Text;

class Program
{
    static void Main()
    {
        string input = @"Hello\uD83D\uDE00World"; // \uD83D\uDE00 是 😀 的代理对
        string unescapedString = UnescapeString(input);

        Console.WriteLine(unescapedString); // 输出: Hello😀World
    }

    static string UnescapeString(string input)
    {
        StringBuilder result = new StringBuilder();
        int i = 0;
        while (i < input.Length)
        {
            if (input[i] == '\\' && i + 1 < input.Length)
            {
                switch (input[i + 1])
                {
                    case 'u':
                        // 处理 \uHHHH 格式的 Unicode 转义字符
                        if (i + 6 <= input.Length)
                        {
                            string hexValue = input.Substring(i + 2, 4);
                            int charCode = Convert.ToInt32(hexValue, 16);
                            result.Append(char.ConvertFromUtf32(charCode));
                            i += 6;
                        }
                        else
                        {
                            result.Append(input[i]);
                            i++;
                        }
                        break;
                    default:
                        result.Append(input[i]);
                        i++;
                        break;
                }
            }
            else
            {
                result.Append(input[i]);
                i++;
            }
        }
        return result.ToString();
    }
}

5. 总结

  • 使用 Regex.Unescape 可以快速还原字符串中的转义字符。
  • 手动处理转义字符时,可以使用 switchif 语句逐个替换。
  • 对于 Unicode 转义字符和代理对,需要额外处理。
  • 根据需求选择合适的方法还原转义字符。
相关推荐
tuokuac1 分钟前
Redis 的相关文件作用
数据库·redis·缓存
dbdr090129 分钟前
Linux 入门到精通,真的不用背命令!零基础小白靠「场景化学习法」,3 个月拿下运维 offer,第二十六天
linux·运维·服务器·网络·python·学习
冷冷的菜哥1 小时前
ASP.NET Core文件分片上传
c#·asp.net·asp.net core·文件分片上传
大白的编程日记.1 小时前
【Linux学习笔记】信号的深入理解之软件条件产生信号
linux·笔记·学习
鹧鸪云光伏与储能软件开发1 小时前
投资储能项目能赚多少钱?小程序帮你测算
运维·数据库·小程序·光伏·光伏设计软件·光伏设计
buyutang_1 小时前
C/C++ Linux系统编程:线程控制详解,从线程创建到线程终止
linux·c语言·c++·学习
云的牧人1 小时前
Ubuntu 22 redis集群搭建
linux·运维·ubuntu
siriuuus1 小时前
Linux 磁盘扩容及分区相关操作实践
linux·运维·服务器
To_再飞行2 小时前
K8s 存储配置资源
linux·云原生·容器·kubernetes
小猪写代码2 小时前
Ubuntu 文件权限管理
linux·ubuntu