Regex to remove only special special characters from a string

I would like to write a regular expression that removes special characters for the following reason:

  • To remove the space character
  • @, &, ', (, ), <, >Or#

I wrote this regex that successfully removes spaces:

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

But I would like to update / change it so that it can remove the characters above that I was talking about.

Can someone help me with this?

+4
source share
4 answers
 string username = Regex.Replace(_username, @"(\s+|@|&|'|\(|\)|<|>|#)", "");
+8
source

use character set [charsgohere]

string removableChars = Regex.Escape(@"@&'()<>#");
string pattern = "[" + removableChars + "]";

string username = Regex.Replace(username, pattern, "");
+6
source

Linq :

 string source = ...

 string result = string.Concat(source
   .Where(c => !char.IsWhiteSpace(c) && 
                c != '(' && c != ')' ...));

, :

 HashSet<char> skip = new HashSet<char>() {
   '(', ')', ... 
 };

 ... 

 string result = string.Concat(source
   .Where(c => !char.IsWhiteSpace(c) && !skip.Contains(c)));
+3
source

You can easily use the Replace Regex function:

string a = "ash&#<>fg  fd";
a= Regex.Replace(a, "[@&'(\\s)<>#]","");
+3
source

Source: https://habr.com/ru/post/1668828/


All Articles