问题
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?
回答1:
string username = Regex.Replace(_username, @"(\s+|@|&|'|\(|\)|<|>|#)", "");
回答2:
use a character set [charsgohere]
string removableChars = Regex.Escape(@"@&'()<>#");
string pattern = "[" + removableChars + "]";
string username = Regex.Replace(username, pattern, "");
回答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)));
回答4:
You can easily use the Replace function of the Regex:
string a = "ash&#<>fg fd";
a= Regex.Replace(a, "[@&'(\\s)<>#]","");
来源:https://stackoverflow.com/questions/42045115/regex-for-removing-only-specific-special-characters-from-string