c# 4.0 - c#替换字符串中除白名单字符以外的所有其他字符

本文关键字:字符 其他 名单 替换 字符串 白名单 | 更新日期: 2023-09-27 18:02:29

我有一个应用程序中允许的字符列表。1234567890 abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz .,'()?!#$%^*;:+=-_

我想要的是,如果我的字符串包含任何字符,然后上面它将被替换为string.empty

c# 4.0 - c#替换字符串中除白名单字符以外的所有其他字符

如果你有一个列表允许的字符,我建议测试这个列表;(Linq):

  // HashSet is efficient to find items O(1)
  private static HashSet<char> s_Allowed = new HashSet<char>(
    @"1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.,'()?!#$%^*;:+=");
  ...
  string source = "123~~~456";
  // "123456"
  string result = string.Concat(source
    .Where(c => s_Allowed.Contains(c)));

您可以使用正则表达式替换。试试这个:

public static string formatToken(string token)
    {
        //To prevent null exception
        if (string.IsNullOrWhiteSpace(token)) return token;
        Regex rgx = new Regex("[^a-zA-Z0-9 .,'()?!#$%*;:+=-_]"); //Maybe some characters need to be scaped. 
        return rgx.Replace(token, "");
    }
相关文章: