【问题标题】:How do I remove all non alphanumeric word from a List<string>如何从 List<string> 中删除所有非字母数字单词
【发布时间】:2016-01-14 00:30:22
【问题描述】:

如何从字符串列表中删除所有非字母数字单词 (List&lt;string&gt;)?

我找到了这个正则表达式!word.match(/^[[:alpha:]]+$/),但在 C# 中,我怎样才能获得一个只包含纯字母数字字符串的新列表?

【问题讨论】:

  • 如果是 c# 那么使用 linq list.Where(x =&gt; Regex.IsMatch(x, @"^[a-zA-Z0-9]$")).ToList();
  • 您想从所有字符串中删除所有非字母数字字符?或者您想要一个仅包含纯字母数字字符串的新列表?
  • 我想要一个只包含纯字母数字字符串的新列表
  • @M.kazemAkhgary 不应该是list.Where(x =&gt; Regex.IsMatch(x, @"[a-zA-Z0-9]*")).ToList(); 吗?
  • @Thomas 哦,是的。我忘了。模式应该是^[a-zA-Z0-9]*$

标签: c# regex


【解决方案1】:

您可以为此使用 LINQ。假设您的字符串中有 theList(或数组或其他):

var theNewList = theList.Where(item => item.All(ch => char.IsLetterOrDigit(ch)));

如果需要,请在末尾添加 .ToList().ToArray()。这是因为String 类实现了IEnumerable&lt;char&gt;

【讨论】:

  • 其实[[:alpha:]]类只匹配字母,所以必须使用Char.IsLetter()。但是,它可能是 OP 正则表达式问题 :)
  • OP 表示字母数字。所以Char.IsLetterOrDigit是正确的
  • OP 需要 alphanumeric 字符串,我假设这包括数字。问题中的正则表达式只是他在其他地方找到的一个例子。
【解决方案2】:
  Regex rgx = new Regex("^[a-zA-Z0-9]*$");
  List<string> list = new List<string>() { "aa", "a", "kzozd__" ,"4edz45","5546","4545asas"};
  List<string> list1 = new List<string>();
  foreach (var item in list)
  {
     if (rgx.Match(item).Success)
     list1.Add(item);
  }

【讨论】:

    【解决方案3】:

    使用 LINQ + 正则表达式,您可以这样使用:

    list = list.Where(s => Regex.IsMatch(s, "^[\\p{L}0-9]*$")).ToList();
    

    ^[\\p{L}0-9]*$ 可以识别 Unicode 字母数字字符。如果您只想使用 ASCII,^[a-zA-Z0-9]*$ 也可以。

    【讨论】:

      【解决方案4】:

      有一个静态辅助函数可以从列表中删除所有非字母数字字符串:

          public static List<string> RemoveAllNonAlphanumeric(List<string> Input)
          {
              var TempList = new List<string>();
              foreach (var CurrentString in Input)
              {
                  if (Regex.IsMatch(CurrentString, "^[a-zA-Z0-9]+$"))
                  {
                      TempList.Add(CurrentString);
                  }
              }
              return TempList;
          }
      

      【讨论】:

      • 您的代码将返回包含至少一个字母数字字符的所有字符串
      猜你喜欢
      • 1970-01-01
      • 2014-10-19
      • 2012-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-19
      • 1970-01-01
      相关资源
      最近更新 更多