0

[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

6
  • Have you tried string invalidChars = @"[^A-Za-zÀ-ÖØ-öø-ÿ0-9\s\.\-\&\,\'\(\)_\/\""\!\:\%]"; ? Commented Jul 7, 2021 at 9:13
  • It's not completely clear to me what you want. On the one hand you preset a single regex, and then say you want the inverse of that regex. That's whole different ball game from what you then show you want (a method that takes any regex and "inverts" it). So which of the 2 are you actually looking for? Commented Jul 7, 2021 at 9:19
  • the regex serves as validator, if it does not match, some characters are wrong and we return an error...YET!! we receive data from a third party too...and we have to take them data...I just want to remove non matching character, using the same regex Commented Jul 7, 2021 at 9:26
  • the idea is to have only one regex to maintain instead of two, in case we add/remove characters Commented Jul 7, 2021 at 9:26
  • Why not only use the inverse regex? For validation you just check if it has 0 matches -> valid. That way you only have 1 regex to maintain (and it's easy to get the inverse of your allowed set) and you gain all the functionality you seem to be looking for? Commented Jul 7, 2021 at 9:47

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.