【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 转义字符和代理对,需要额外处理。
  • 根据需求选择合适的方法还原转义字符。
相关推荐
cimeo43 分钟前
【C 学习】06-算法&程序设计举例
c#
百锦再1 小时前
.NET 的 WebApi 项目必要可配置项都有哪些?
java·开发语言·c#·.net·core·net
獭.獭.2 小时前
Linux -- 文件【下】
linux·服务器·文件系统·软硬链接·inode·ext2
破刺不会编程4 小时前
socket编程UDP
linux·运维·服务器·网络·c++·网络协议·udp
xiao-xiang7 小时前
redis-保姆级配置详解
数据库·redis
白鹭9 小时前
MySQL(多表查询练习)
数据库·mysql
NEXU510 小时前
Linux:套接字
linux·服务器·网络
morliz子轩11 小时前
基于WSL搭建Ubuntu 22.04.x LTS开发环境
linux·运维·ubuntu
WYH28712 小时前
C#控制台输入(Read()、ReadKey()和ReadLine())
开发语言·c#
Janspran12 小时前
嵌入式linux学习 -- 进程和线程
linux·运维·学习