How to convert a string containing escape characters to a string

前端 未结 4 2212
心在旅途
心在旅途 2020-12-11 19:25

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

Here is a sample string

\"test\\40gmail.com\"

A

4条回答
  •  春和景丽
    2020-12-11 19:47

    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.

提交回复
热议问题