在c#中,我可以将字符串值转换为字符串文字,我将在代码中看到它的方式吗?我想用转义序列替换制表符,换行符等。

如果这段代码:

Console.WriteLine(someString);

生产:

Hello
World!

我想要这样的代码:

Console.WriteLine(ToLiteral(someString));

生产:

\tHello\r\n\tWorld!\r\n

当前回答

Roslyn在NuGet上的Microsoft.CodeAnalysis.CSharp包中有一个方法:

private static string ToLiteral(string valueTextForCompiler)
{
    return Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(valueTextForCompiler, false);
}

显然,这在最初的问题时并不存在,但它可能会帮助那些从谷歌搜索到这里的人。

其他回答

public static class StringHelpers
{
    private static Dictionary<string, string> escapeMapping = new Dictionary<string, string>()
    {
        {"\"", @"\\\"""},
        {"\\\\", @"\\"},
        {"\a", @"\a"},
        {"\b", @"\b"},
        {"\f", @"\f"},
        {"\n", @"\n"},
        {"\r", @"\r"},
        {"\t", @"\t"},
        {"\v", @"\v"},
        {"\0", @"\0"},
    };

    private static Regex escapeRegex = new Regex(string.Join("|", escapeMapping.Keys.ToArray()));

    public static string Escape(this string s)
    {
        return escapeRegex.Replace(s, EscapeMatchEval);
    }

    private static string EscapeMatchEval(Match m)
    {
        if (escapeMapping.ContainsKey(m.Value))
        {
            return escapeMapping[m.Value];
        }
        return escapeMapping[Regex.Escape(m.Value)];
    }
}

我试图将ToVerbatim添加到Hallgrim公认的答案中:

private static string ToLiteral(string input)
{
    using (var writer = new StringWriter())
    {
        using (var provider = CodeDomProvider.CreateProvider("CSharp"))
        {
            provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, new CodeGeneratorOptions { IndentString = "\t" });
            var literal = writer.ToString();
            literal = literal.Replace(string.Format("\" +{0}\t\"", Environment.NewLine), "");
            return literal;
        }
    }
}

private static string ToVerbatim(string input)
{
    string literal = ToLiteral(input);
    string verbatim = "@" + literal.Replace(@"\r\n", Environment.NewLine);
    return verbatim;
}

如果JSON约定对于你想要转义的未转义字符串足够,并且你已经使用了JSON。NET (Newtonsoft.Json)在你的项目中(它有一个相当大的开销),你可以像下面这样使用这个包:

using System;
using Newtonsoft.Json;

public class Program
{
    public static void Main()
    {
        Console.WriteLine(ToLiteral(@"abc\n123"));
    }

    private static string ToLiteral(string input)
    {
        return JsonConvert.DeserializeObject<string>("\"" + input + "\"");
    }
}

代码:

string someString1 = "\tHello\r\n\tWorld!\r\n";
string someString2 = @"\tHello\r\n\tWorld!\r\n";

Console.WriteLine(someString1);
Console.WriteLine(someString2);

输出:

    Hello
    World!

\tHello\r\n\tWorld!\r\n

使用Regex.Escape(字符串):

正则表达式。Escape转义最小字符集(,*,+,?,|,{,[, (,), ^, $,。, #和空白),用转义符替换它们 代码。