Regex for removing only specific special characters from string

两盒软妹~` 提交于 2020-06-11 03:04:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!