Link to home
Start Free TrialLog in
Avatar of HubertFarnsworth
HubertFarnsworthFlag for United States of America

asked on

Removing Special Characters from a String in C#

Good Day -
I have a C# application which reads from a DB wherein must of the data is stored in Blobs/Text. The data is actually entered via another product which allows users to enter special characaters that get wrecked when put into a C# string. For example, if the user copies email text into the DB they get characters like  (146) which gets changed into â¬" when read into a string.

I already use the following to remove non-print characters and it works well:
string fieldData = "";
string pattern1 = @"[\x01-\x1F]+";
<fieldData is loaded from DataTable>
fieldData = Regex.Replace(fieldData, pattern1, "", RegexOptions.IgnoreCase);

I'm wondering if I need to do the same with characters 128-159. If so, how would I code that pattern for RegEx? I ask because I am quite unfamiliar with the encoding for these characters and have no idea how to code it.

Any assistance would be appreciated.
Avatar of ZachSmith
Flag of United States of America image

This is probably a situation where you want to define what is a GOOD value, and not what is a BAD value. I say this because there are likely many more bad values than good, and if you start kicking out all bad values you may find yourself continually updating the Regex. So what values do you want to allow in the string? I assume you want at least these:

a-z A-Z 0-9 !@#$%^&*(){}[]:';"/?.>,<~`-_=+\|

Are there any other values you need to accept?
I would guess that is a character encoding problem.

So the question is, if you can so easily drop those characters. And the other question is (most likely more diffucult to answere) what kind of encoding the other 'application' is using. <- knowing that it should be fairly easy to convert forth and back without regexp stuff.
Avatar of HubertFarnsworth


ZachSmith -

No, those are pretty much the only characters I'd want to keep.
Avatar of ZachSmith
Flag of United States of America image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Bravo! Thank you very much. It works exactly as I'd hoped.