Regex for removing only specific special characters from string

前端 未结 4 1264
梦如初夏
梦如初夏 2021-01-02 16:28

I\'d like to write a regex that would remove the special characters on following basis:

  • To remove white space character
  • @, &
相关标签:
4条回答
  • 2021-01-02 16:51
     string username = Regex.Replace(_username, @"(\s+|@|&|'|\(|\)|<|>|#)", "");
    
    0 讨论(0)
  • 2021-01-02 16:56

    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)));
    
    0 讨论(0)
  • 2021-01-02 17:03

    use a character set [charsgohere]

    string removableChars = Regex.Escape(@"@&'()<>#");
    string pattern = "[" + removableChars + "]";
    
    string username = Regex.Replace(username, pattern, "");
    
    0 讨论(0)
  • 2021-01-02 17:16

    You can easily use the Replace function of the Regex:

    string a = "ash&#<>fg  fd";
    a= Regex.Replace(a, "[@&'(\\s)<>#]","");
    
    0 讨论(0)
提交回复
热议问题