Unescape escaped string?

We save the ContentDelimiter configuration (which we use to delimit the content) in the database as a string (which can be a "tab", i.e. \ t or a new line \ r \ n)

Later we would like to use this configuration, how would I go about converting \t (which is a string, not a chat) to the char tab?

Example:

 string delimiterConfig = config.GetDelimiter(); char[] delimiter = ConvertConfig(delimiterConfig); 

How ConvertConfig will look like it will parse all escaped strings back into characters so that the string "\ t" becomes \t char.

Any elegant solutions without the use of case statements and replacements?

+4
source share
5 answers

Here's an elegant solution with a switch statement, Regex.Replace Method and custom MatchEvaluator :

 var input = @"This is indented:\r\n\tHello World"; var output = Regex.Replace(input, @"\\[rnt]", m => { switch (m.Value) { case @"\r": return "\r"; case @"\n": return "\n"; case @"\t": return "\t"; default: return m.Value; } }); Console.WriteLine(output); 

Output:

  This is indented:
         Hello world
+4
source

If with the β€œbest” solution you speak faster:

 static String Replace(String input) { if (input.Length <= 1) return input; // the input string can only get shorter // so init the buffer so we won't have to reallocate later char[] buffer = new char[input.Length]; int outIdx = 0; for (int i = 0; i < input.Length; i++) { char c = input[i]; if (c == '\\') { if (i < input.Length - 1) { switch (input[i + 1]) { case 'n': buffer[outIdx++] = '\n'; i++; continue; case 'r': buffer[outIdx++] = '\r'; i++; continue; case 't': buffer[outIdx++] = '\t'; i++; continue; } } } buffer[outIdx++] = c; } return new String(buffer, 0, outIdx); } 

This is significantly faster than using Regex. Especially when I tested this input:

 var input = new String('\\', 0x1000); 

If β€œbetter,” you realize that it’s easier to read and maintain, then the Regex solution will probably win. There may be errors in my decision; I did not test it very carefully.

+4
source

For a limited set of basic ASCII delimiters, you also have a simple solution:

 Regex.Unescape(input) 

You can read all about this in the MSDN documentation, but it basically works with all Regex delimiters and spaces.

Remember that it throws unknown escape sequences.

+2
source

If better, you referenced supported escape sequences, then I suggest you check out my answer to a question called: Evaluate escaped string , which handles standard escape sequences, octal escape sequences, and Unicode escape sequences. Hope you find this solution more elegant and suitable for your needs.

+1
source

What about the ToCharArray method?

 string x = "\r\n"; char[] delimeter = x.ToCharArray(); 
0
source

All Articles