phil123456
phil123456

Reputation: 1648

C# - regex - replace non matching characters

[there are similar questions but none is giving a valid answer for my needs]

I allow user to input text matching this regex :

string validChars = @"^[A-Za-zÀ-ÖØ-öø-ÿ0-9\s\.\-\&\,\'\(\)_\/\""\!\:\%]*?$";

what I want to do is to remove characters that do NOT match that regex

how can I INVERT the regex so I can do

invalidChars  = some_trick_to_invert_regex(validChars); 
text = Regex.Replace(text, invalidChars , "");

thanks for your help

Upvotes: 0

Views: 431

Answers (1)

oRoiDev
oRoiDev

Reputation: 349

You can whitelist the characters you want to keep by placing the ^ inside the brackets. Example:

string validChars = @"[^A-Za-zÀ-ÖØ-öø-ÿ0-9\s\.\-\&\,\'\(\)_\/\""\!\:\%]";
string test = "abc#de";
var result = Regex.Replace(test, validChars, ""); //abcde

Upvotes: 2

Related Questions