【问题标题】:Split a string of Number and characters拆分一串数字和字符
【发布时间】:2014-02-11 03:17:29
【问题描述】:

我有一个列表 liRoom,其中包含一个字母数字和字母字符串例如

List<string> liRoom = new List<string>() {"Room1","Room2","Room3",  
                                         "Room4","Hall","Room5","Assembly",  
                                         "Room6","Room7","Room8","Room9};

这个列表是字母数字和字母类型,所以我想从这个字符串列表中获取最大数值。
我曾尝试过这样做

var ss = new Regex("(?<Alpha>[a-zA-Z]+)(?<Numeric>[0-9]+)");  
List<int> liNumeric = new List<int>();  
foreach (string st in liRoom)  
{   
var varMatch = ss.Match(st);  
liNumeric.Add(Convert.ToInt16(varMatch.Groups["Numeric"].Value));   
}  
int MaxValue = liNumeric.Max();// Result Must be 9 from above Example.

还有

 List<int> liNumeric = new List<int>();  
 foreach (string st in liRoom)  
 {   
   liNumeric.Add( int.Parse(new string(st.Where(char.IsDigit).ToArray())));   
 }  
 int MaxValue = liNumeric.Max();// Result Must be 9 from above Example.

但是当stHall,Assembly 时两者都显示错误
帮帮我怎么做。

【问题讨论】:

    标签: c# regex string split


    【解决方案1】:

    在您的代码中出现异常的原因很少。我为那些可能的例外情况添加了一些条件。

    List<int> liNumeric = new List<int>();  
     foreach (string st in liRoom)  
     { 
       // int.Parse will fail if you don't have any digit in the input 
       if(st.Any(char.IsDigit))
       {
           liNumeric.Add(int.Parse(new string(st.Where(char.IsDigit).ToArray()))); 
       }
    
     }  
     if (liNumeric.Any()) //Max will fail if you don't have items in the liNumeric
     {
         int MaxValue = liNumeric.Max();
     }
    

    【讨论】:

      【解决方案2】:

      请尝试以下方法:

      List<string> liRoom = new List<string>() {"Room1","Room2","Room3",  
                                               "Room4","Hall","Room5","Assembly",  
                                               "Room6","Room7","Room8","Room9"};
      
      
      var re = new Regex(@"\d+");
      
      int max = liRoom.Select(_ => re.Match(_))
                      .Where(_ => _.Success)
                      .Max( _ => int.Parse(_.Value));
      
      /* 
         max = 9 
      */
      

      【讨论】:

      • 为什么我不喜欢 lambda 表达式中的下划线“_”?
      【解决方案3】:

      你不需要foreach,一个语句就能搞定:

      int value = liRoom.Where(x => x.Any(char.IsDigit))
                  .Select(x => Convert.ToInt32(new String(x.Where(char.IsDigit).ToArray())))
                  .Max();
      

      这似乎奇怪,但它正在工作。 :)

      【讨论】:

      • 不错,但 Damith 很快
      【解决方案4】:

      您应该通过检查匹配是否成功在代码中添加以下内容

      if (varMatch.Success)
      {
           liNumeric.Add(Convert.ToInt16(varMatch.Groups["Numeric"].Value));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多