Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string containing escape characters to a string

Tags:

c#

.net

I have a string that is returned to me which contains escape characters.

Here is a sample string

"test\40gmail.com"

As you can see it contains escape characters. I need it to be converted to its real value which is

"[email protected]"

How can I do this?

like image 526
Martin Avatar asked Jul 20 '12 17:07

Martin


People also ask

How do I ignore an escape character in a string?

An escape sequence is a set of characters used in string literals that have a special meaning, such as a new line, a new page, or a tab. For example, the escape sequence \n represents a new line character. To ignore an escape sequence in your search, prepend a backslash character to the escape sequence.

How do I print an escape character in a string?

, \t, \r, etc., What if we want to print a string which contains these escape characters? We have to print the string using repr() inbuilt function. It prints the string precisely what we give.

How do you check for escape characters in a string?

This means that every escape sequence will consist of "\\" two backslashes, followed by one of {n, b, r, t, f, ", \}, or a 'u' character, plus exactly four hexadecimal [0-F] digits. If you just want to know whether or not the original String contains escape sequences, search for "\\" in the Apache-fied string.


1 Answers

If you are looking to replace all escaped character codes, not only the code for @, you can use this snippet of code to do the conversion:

public static string UnescapeCodes(string src) {
    var rx = new Regex("\\\\([0-9A-Fa-f]+)");
    var res = new StringBuilder();
    var pos = 0;
    foreach (Match m in rx.Matches(src)) {
        res.Append(src.Substring(pos, m.Index - pos));
        pos = m.Index + m.Length;
        res.Append((char)Convert.ToInt32(m.Groups[1].ToString(), 16));
    }
    res.Append(src.Substring(pos));
    return res.ToString();
}

The code relies on a regular expression to find all sequences of hex digits, converting them to int, and casting the resultant value to a char.

like image 134
Sergey Kalinichenko Avatar answered Nov 14 '22 22:11

Sergey Kalinichenko