user3038537
user3038537

Reputation: 9

Replace unprintable characters from a string

I'm creating a logic to replace the unprintable characters from a string with a space, just that I'm confused if it is the same ASCII characters and Unicode characters, I have reviewed about how to do using regex.replace function but I don't understand how to validate if the character from the string is between the below conditions.

This is the requirement I got, replace with a space:

I have tried this (I believe this works for ASCII characters) but do I handle unicode characters?

newPartNum = Regex.Replace(PartNum, @"[^\u0020-\u007E]", " ");

Any help would be appreciate it.

Upvotes: 0

Views: 697

Answers (2)

Jeff R.
Jeff R.

Reputation: 1521

Take a look at the IsControl method of the Char struct type. If for no other reason it talks about the range of control characters.

Also, using a range of valid chars in your regex is certainly doable but may get messy when dealing with Unicode chars since the range is large. Might be better to just look for the characters you need to replace. Again, look at the Char.IsControl method for details.

Upvotes: 0

Arpit Gupta
Arpit Gupta

Reputation: 1277

With the help of Linq, You can check if the character is control character. What I am targeting below is to remove the control characters from string -

string str = ""; // Whatever your string is. Comes here.
string res = new string(str.Where(c => !char.IsControl(c)).ToArray());

Upvotes: 2

Related Questions