简体   繁体   中英

Convert ASCII hex codes to character in “mixed” string

Is there a method, or a way to convert a string with a mix of characters and ASCII hex codes to a string of just characters?

eg if I give it the input Hello\\x26\\x2347\\x3bWorld it will return Hello/World ?

Thanks

Quick and dirty:

    static void Main(string[] args)
    {
        Regex regex = new Regex(@"\\x[0-9]{2}");
        string s = @"Hello\x26\x2347World";
        var matches = regex.Matches(s);
        foreach(Match match in matches)
        {
            s = s.Replace(match.Value, ((char)Convert.ToByte(match.Value.Replace(@"\x", ""), 16)).ToString());
        }
        Console.WriteLine(s);
        Console.Read();
    }

And use HttpUtility.HtmlDecode to decode the resulting string.

I'm not sure about those specific character codes but you might be able to do some kind of regex to find all the character codes and convert only them. Though if the character codes can be varying lengths it might be difficult to make sure that they don't get mixed up with any normal numbers/digits in the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM