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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

use a character set [charsgohere]

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

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

Method 3

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

Method 4

You can easily use the Replace function of the Regex:

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

Method 5

import re
string1 = "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="39080b790a0d">[email protected]</a>#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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x