Convert a Unicode string to an escaped ASCII string

前端 未结 9 1402
广开言路
广开言路 2020-11-22 04:00

How can I convert this string:

This string contains the Unicode character Pi(π)

into an escaped A

9条回答
  •  醉话见心
    2020-11-22 04:59

    A small patch to @Adam Sills's answer which solves FormatException on cases where the input string like "c:\u00ab\otherdirectory\" plus RegexOptions.Compiled makes the Regex compilation much faster:

        private static Regex DECODING_REGEX = new Regex(@"\\u(?[a-fA-F0-9]{4})", RegexOptions.Compiled);
        private const string PLACEHOLDER = @"#!#";
        public static string DecodeEncodedNonAsciiCharacters(this string value)
        {
            return DECODING_REGEX.Replace(
                value.Replace(@"\\", PLACEHOLDER),
                m => { 
                    return ((char)int.Parse(m.Groups["Value"].Value, NumberStyles.HexNumber)).ToString(); })
                .Replace(PLACEHOLDER, @"\\");
        }
    

提交回复
热议问题