Reputation: 3823
I'd like to write a regex that would remove the special characters on following basis:
@
, &
, '
, (
, )
, <
, >
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?
Upvotes: 15
Views: 98475
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
Reputation: 174435
use a character set [charsgohere]
string removableChars = Regex.Escape(@"@&'()<>#");
string pattern = "[" + removableChars + "]";
string username = Regex.Replace(username, pattern, "");
Upvotes: 11
Reputation: 34152
You can easily use the Replace function of the Regex:
string a = "ash&#<>fg fd";
a= Regex.Replace(a, "[@&'(\\s)<>#]","");
Upvotes: 4
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
Reputation: 2930
string username = Regex.Replace(_username, @"(\s+|@|&|'|\(|\)|<|>|#)", "");
Upvotes: 40