拆分一串数字和字符

时间:2014-02-11 03:17:30

标签: c# regex string split

我有一个List liRoom,其中包含一个字母数字和字母字符串For Example

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时,两者都显示错误 帮帮我怎么做。

4 个答案:

答案 0 :(得分:3)

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

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();
 }

答案 1 :(得分: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 
*/

答案 2 :(得分:1)

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

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

答案 3 :(得分:1)

您不需要foreach,可以使用一个语句完成:

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

似乎奇数但它正在运作。 :)