从字符串末尾提取整数

时间:2016-05-13 08:22:04

标签: c# string list

我在List<string>()

中有多个ID
List<string> IDList = new List<string>() {
"ID101",     //101
"I2D102",    //102
"103",       //103
"I124D104",  //104
"ID-105",    //105
"-1006" };   //1006

规则:字符串始终以id为n,其长度为1到n,仅为int

我需要将它们提取到int值。但我的解决方案不起作用

List<int> intList = IDList.Select(x => int.Parse(Regex.Match(x, @".*\d*").Value)).ToList();

5 个答案:

答案 0 :(得分:4)

如果ID始终在最后,您可以使用LINQ解决方案而不是Regex

var query = IDList.Select(id => 
    int.Parse(new string(id.Reverse()
        .TakeWhile(x => char.IsNumber(x))
        .Reverse().ToArray())));

这个想法是从最后一个角色中取出角色直到找不到数字。无论你得到什么,你都将其转换为int。这个解决方案的好处在于它真正代表了您指定的内容。

答案 1 :(得分:4)

嗯,根据

  

规则:字符串总是以长度为1到n的id结尾   仅为int

模式只不过是

  [0-9]{1,n}$

  [0-9] - ints only 
  {1,n} - from 1 to n (both 1 and n are included)
  $     - string always ends with

可能的实现可能是这样的

  int n = 5; //TODO: put actual value
  String pattern = "[0-9]{1," + n.ToString() + "}$";

  List<int> intList = IDList
    .Select(line => int.Parse(Regex.Match(line, pattern).Value))
    .ToList();

如果有一些断行,请说"abc"(并且您希望过滤掉):

  List<int> intList = IDList
    .Select(line => Regex.Match(line, pattern))
    .Where(match => match.Success)
    .Select(match => int.Parse(match.Value))
    .ToList(); 

答案 2 :(得分:2)

这是另一种LINQ方法,如果数字始终在最后且负值不可能,则该方法有效。跳过无效字符串:

 List<int> intList = IDList
    .Select(s => s.Reverse().TakeWhile(Char.IsDigit))
    .Where(digits => digits.Any())
    .Select(digits => int.Parse(String.Concat(digits.Reverse())))
    .ToList();

(编辑:类似于Ian's approach

答案 3 :(得分:1)

以下代码从集合中提取最后一个id为整数,并忽略它们以无整数值

结尾
List<int> intList = IDList.Where(a => Regex.IsMatch(a, @"\d+$") == true)
   .Select(x => int.Parse(Regex.Match(x, @"\d+$").Value)).ToList();

答案 4 :(得分:-2)

我假设你想要最后的数字:

var res = IDList.Select(x => int.Parse(Regex.Match(x, @"\d+$").Value)).ToList();