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

news/2025/2/27 12:50:44

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


1. 使用 Regex.Unescape 方法

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

示例代码:
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 语句逐个替换。

示例代码:
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 转义字符,可以扩展上述方法。

示例代码:
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 来处理。

示例代码:
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 转义字符和代理对,需要额外处理。
  • 根据需求选择合适的方法还原转义字符。

http://www.niftyadmin.cn/n/5868700.html

相关文章

如何正确选择百度蜘蛛池服务

Tbaidutopseo 在竞争激烈的互联网环境中&#xff0c;网站若想获得更多流量和曝光&#xff0c;提升在搜索引擎中的排名至关重要。百度蜘蛛池服务作为一种能够帮助网站吸引百度蜘蛛抓取&#xff0c;进而提高网站收录量和排名的工具&#xff0c;受到众多网站所有者的关注。然而&a…

千峰React:函数组件使用(3)

多组态进行正确记忆 首先看这个代码 import { useState } from reactfunction App() {const [count, setCount] useState(0)const [count2, setCount2] useState(0)const [count3, setCount3] useState(0)const handleClick () > {setCount(count 1)}return (<div&…

(0)阿里云大模型ACP-考试回忆

这两天通过了阿里云大模型ACP考试&#xff0c;由于之前在网上没有找到真题&#xff0c;导致第一次考试没有过&#xff0c;后面又重新学习了一遍文档才顺利通过考试&#xff0c;这两次考试内容感觉考试题目90%内容是覆盖的&#xff0c;后面准备分享一下每一章的考题&#xff0c;…

贪心算法:JAVA从理论到实践的探索

在计算机科学领域,贪心算法是一种简单而高效的算法设计策略,广泛应用于优化问题的求解。它通过在每一步选择中都采取当前状态下最优的选择,以期望最终得到全局最优解。本文将深入探讨贪心算法的原理、应用场景,并通过具体代码示例,帮助读者更好地理解和掌握这一算法。 一…

深度剖析Seata源码:解锁分布式事务处理的核心逻辑

文章目录 写在文章开头如何使用源码(配置转掉)基于AT模式详解Seata全链路流程Seata服务端启动本地服务如何基于GlobalTransaction注解开启事务客户端如何开启分布式事务RM和TC如何协调处理分支事务RM生成回滚日志事务全局提交与回滚小结参考写在文章开头 在当今分布式系统日益…

已经有私钥的情况下,mac如何配置私钥

在 macOS 上配置现有的私钥&#xff0c;通常是为了能够使用 SSH 无密码登录远程服务器。以下是一步步的配置过程&#xff1a; 1. 将私钥文件添加到 ~/.ssh/ 目录 如果你的私钥文件&#xff08;例如 id_rsa 或其他&#xff09;不在 ~/.ssh/ 目录下&#xff0c;首先需要将私钥文…

FFmpeg视频处理入门级教程

一、FFmpeg常规处理流程 #mermaid-svg-W8X1llNEyuYptV3I {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-W8X1llNEyuYptV3I .error-icon{fill:#552222;}#mermaid-svg-W8X1llNEyuYptV3I .error-text{fill:#552222;str…

深入浅出ES6:现代JavaScript的基石

ES6&#xff08;ECMAScript 2015&#xff09;是JavaScript语言的一次重大更新&#xff0c;引入了许多新特性&#xff0c;使JavaScript更加强大、优雅和易于维护。这些特性已经成为现代JavaScript开发的基石&#xff0c;掌握它们对于任何JavaScript开发者都至关重要。本文将深入…