简体   繁体   中英

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?

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

use a character set [charsgohere]

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

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

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)));

You can easily use the Replace function of the Regex:

string a = "ash&#<>fg  fd";
a= Regex.Replace(a, "[@&'(\\s)<>#]","");
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

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