Search code examples
c#asp.netregexc#-4.0special-characters

Regex for removing only specific special characters from string


I'd like to write a regex that would remove the special characters on following basis:

  • To remove white space character
  • @, &, ', (, ), <, > or #

I have written this regex which removes whitespaces successfully:

 string username = Regex.Replace(_username, @"\s+", "");

But I'd like to upgrade/change it so that it can remove the characters above that I mentioned.

Can someone help me out with this?


Solution

  •  string username = Regex.Replace(_username, @"(\s+|@|&|'|\(|\)|<|>|#)", "");