Search code examples
c#rfc3986

How unescape RFC 3986 string


I've a RFC 3986 encoded string in the form %x##. For example the space character is encoded as %x20 instead of %20. How can I decode it in C#? Using the decode method of Uri, HttpUtility or WebUtility classes the string was not decoded.


Solution

  • You can try regular expressions in order to Replace all %x## as well as %## matches:

      using System.Text.RegularExpressions;
    
      ...
    
      string demo = "abc%x20def%20pqr";
    
      string result = Regex.Replace(
          demo, 
        "%x?([0-9A-F]{2})", 
          m => ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(), 
          RegexOptions.IgnoreCase);
    
      Console.Write(result);
    

    Outcome:

      abc def pqr