Ninad Kavimandan
Ninad Kavimandan

Reputation: 23

How do I insert an escape character(e.g. "\t") into a string as "\t", not literal tabs?

I'm generating a SQL query for hive using creating a table using C#. The schema of the table is stored in a file, having table properties and delimiter information. While generating the query, I'm specifying the delimiter from as read from the file, but it getting added directly as tabs and not '\t' in case of tab as delimiter.

At first I tried included @ at the beginning, but it didn't work with @"{varname}" format. It did work with '\t' used directly in the string. (@"'\t'"). For now I have set up a condition to insert '\t' directly into the string instead of {varname}.

string delimiter = fileSchema.delimiter.ToString();
string loc = $@"delimited fields terminated by '{delimiter}'"; // generated 
//"delimited fields terminated by '        '"

//workaround for now:
string delimiter = fileSchema.delimiter.ToString();
string loc = delimiter.Equals("\t") ? @"delimited fields terminated by '\t'" : $@"delimited fields terminated by '{delimiter}'";

'\t' is expected instead of actual tabs

Upvotes: 2

Views: 612

Answers (2)

Johnny
Johnny

Reputation: 9519

I have a delimiter that is currently a tab ("\t"), and I'd like to get the escaped version of that string ("\t" / @"\t", i.e. "slash t") - how can I do that?

You could use System.Text.RegularExpressions to convert string to escaped form string, e.g.

string delimiter = Regex.Escape("\t\n");
Console.WriteLine(Regex.Escape(delimiter));
//output: \t\n

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062915

I think what you're saying is:

I have a delimiter that is currently a tab ("\t"), and I'd like to get the escaped version of that string ("\\t" / @"\t", i.e. "slash t") - how can I do that?

is that about right? if so, the next question becomes "using which escape rules?" - presumably you mean C# escape rules, but different .NET languages can have different rules, since this is a compilation thing. In reality, no pre-rolled API exists for this, so your best bet is to write your own escape code that handles the tokens you expect, and replaces them with the escaped form that you expect.

Upvotes: 0

Related Questions