14

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
User987
  • 3,663
  • 15
  • 54
  • 115

5 Answers5

35
 string username = Regex.Replace(_username, @"(\s+|@|&|'|\(|\)|<|>|#)", "");
Mithilesh Gupta
  • 2,800
  • 1
  • 17
  • 17
11

use a character set [charsgohere]

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

string username = Regex.Replace(username, pattern, "");
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
4

I suggest using Linq instead of regular expressions:

 string source = ...

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

In case you have many characters to skip you can organize them into a collection:

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

 ... 

 string result = string.Concat(source
   .Where(c => !char.IsWhiteSpace(c) && !skip.Contains(c)));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
4

You can easily use the Replace function of the Regex:

string a = "ash&#<>fg  fd";
a= Regex.Replace(a, "[@&'(\\s)<>#]","");
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
-1
import re
string1 = "12@34#adf$c5,6,7,ok"
output = re.sub(r'[^a-zA-Z0-9]','',string1)

^ will use for except mention in brackets(or replace special char with white spaces) will substitute with whitespaces then will return in string

result = 1234adfc567ok

manjunath
  • 37
  • 4