Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly escape this string

Tags:

string

c#

I have a string which I am sending to an external print function.
I need to pad the string with backslashes so it prints properly.

Specifically, I need a method which would accept this example input:
This is a string\nwith a line break\ta tab\rand a carriage return.

and output:
This is a string\\nwith a line break\\ta tab\\rand a carriage return.

Do I need to brute force Replace every possible escape character with it's backslashed equivalent?

Tried:
s.Replace("\\","\\\\") Doesn't work because it's looking for a backslash literal.

s.Replace("\n","\\n") obviously works, but what I'm looking for is a generic method.

Edit: Please don't suggest brute force methods, I understand it is no problem to implement such a method. My question was if there is a more universal approach.

like image 466
Rotem Avatar asked Nov 26 '12 20:11

Rotem


1 Answers

private static string EscapeLiterals(string input)
{
    using (var writer = new StringWriter())
    {
        using (var provider = CodeDomProvider.CreateProvider("CSharp"))
        {
            provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
            return writer.ToString();
        }
    }
}

Takes input "\tHello\r\n\tLiterals!" and turns it into "\\tHello\\r\\n\\tLiterals!"

Works for any input - it will get you the escape sequence for anything.

like image 150
caesay Avatar answered Sep 22 '22 22:09

caesay