简体   繁体   English

将ASCII十六进制代码转换为“混合”字符串中的字符

[英]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? 是否存在将字符和ASCII十六进制代码混合的字符串转换为仅字符的字符串的方法或方法?

eg if I give it the input Hello\\x26\\x2347\\x3bWorld it will return Hello/World ? 例如,如果我给它输入Hello\\x26\\x2347\\x3bWorld ,它将返回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. 并使用HttpUtility.HtmlDecode解码结果字符串。

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. 尽管如果字符代码的长度可以变化,则可能很难确保它们不会与字符串中的任何正常数字/数字混淆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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