简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM