【问题标题】:Regex for removing only specific special characters from string用于仅从字符串中删除特定特殊字符的正则表达式
【发布时间】:2017-06-22 01:21:34
【问题描述】:

我想写一个正则表达式,它会在以下基础上删除特殊字符:

  • 删除空白字符
  • @&'()<>#

我已经编写了这个成功删除空格的正则表达式:

 string username = Regex.Replace(_username, @"\s+", "");

但我想升级/更改它,以便它可以删除我提到的上述字符。

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: c# asp.net regex c#-4.0 special-characters


    【解决方案1】:
     string username = Regex.Replace(_username, @"(\s+|@|&|'|\(|\)|<|>|#)", "");
    

    【讨论】:

      【解决方案2】:

      使用字符集[charsgohere]

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

      【讨论】:

        【解决方案3】:

        我建议使用 Linq 而不是 正则表达式

         string source = ...
        
         string result = string.Concat(source
           .Where(c => !char.IsWhiteSpace(c) && 
                        c != '(' && c != ')' ...));
        

        如果您有 许多 个字符要跳过,您可以将它们组织成一个集合:

         HashSet<char> skip = new HashSet<char>() {
           '(', ')', ... 
         };
        
         ... 
        
         string result = string.Concat(source
           .Where(c => !char.IsWhiteSpace(c) && !skip.Contains(c)));
        

        【讨论】:

        • 为什么 Linq 比正则表达式更好?
        • Linq 在上下文中更简单(更具可读性) - 只有一个 Where, - 不是“更好”
        【解决方案4】:

        您可以轻松使用正则表达式的替换功能:

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

        【讨论】:

          【解决方案5】:
          import re
          string1 = "12@34#adf$c5,6,7,ok"
          output = re.sub(r'[^a-zA-Z0-9]','',string1)
          

          ^ 将使用 for except 在括号中提及(或用空格替换特殊字符)将用空格替换然后将返回字符串

          结果 = 1234adfc567ok

          【讨论】:

            猜你喜欢
            • 2011-03-19
            • 2016-05-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-07-26
            相关资源
            最近更新 更多