【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 转义字符和代理对,需要额外处理。
  • 根据需求选择合适的方法还原转义字符。
相关推荐
数字芯片实验室1 分钟前
正则表达式的前世今生
正则表达式
yi个名字5 分钟前
Linux文件系统详解:从入门到精通
linux·运维·服务器
Htht1115 分钟前
【Qt】之【Get√】【Bug】通过值捕获(或 const 引用捕获)传进 lambda,会默认复制成 const
数据库·bug
The Kite19 分钟前
MPLAB X IDE 软件安装与卸载
ide·c#·嵌入式
一棵树长得超出它自己1 小时前
数据库系统学习
数据库
小袁搬码1 小时前
PLSQLDeveloper配置OracleInstantClient连接Oracle数据库
数据库·oracle·pl/sqldeveloper
Lw老王要学习1 小时前
Linux容器篇、第二章_01Ubuntu22 环境下 KubeSphere 容器平台高可用搭建全流程
linux·运维·服务器·k8s·kubesphere·容器化
学习中的码虫1 小时前
MySQL提升
数据库·mysql
染指11102 小时前
35.x64汇编写法(二)
汇编·windows·x64游戏·x64汇编·游戏攻防
張萠飛2 小时前
Linux下如何使用shell脚本导出elasticsearch中某一个index的数据为本地csv文件
linux·运维·elasticsearch