User987
User987

Reputation: 3823

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:

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?

Upvotes: 15

Views: 98475

Answers (5)

manjunath
manjunath

Reputation: 35

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

Upvotes: -1

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174435

use a character set [charsgohere]

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

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

Upvotes: 11

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34152

You can easily use the Replace function of the Regex:

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

Upvotes: 4

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

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

Upvotes: 4

Mithilesh Gupta
Mithilesh Gupta

Reputation: 2930

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

Upvotes: 40

Related Questions