Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removing escaped non printable characters from JsonString

I’m getting JsonString from client API and there is some non-printable characters(escaped) in that jsonString:

"{\"Name\":\"\\u001f\\u001f!#$%&'%\\u0001\"}"

I need to remove all this \u001f, \u0001 strings from my string

Regex.Replace("{\"Name\":\"\\u001f\\u001f!#$%&'%\\u0001\"}", @"[^\u0020-\u007E]", string.Empty)

I tried all regexes and all sanitize functions, nothing works, nothing can catch those strings…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Maybe I’m doing something wrong and you can help me.

>Solution :

Let’s match every \\udddd and analyze the dddd code:

string text = "{\"Name\":\"\\u001f\\u001f!#$%&'%\\u0001\"}";

// {"Name":"!#$%&'%"}
var result = Regex.Replace(text,
  @"\\u(?<value>[0-9A-Fa-f]{4})",
   m => char.IsControl((char) int.Parse(m.Groups["value"].Value, NumberStyles.HexNumber)) 
     ? "" 
     : m.Value);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading