代码之家  ›  专栏  ›  技术社区  ›  Syntax Error ine

如何仅从字符串数组中获取数字?

  •  -2
  • Syntax Error ine  · 技术社区  · 6 年前

    我有一个字符串数组( items )其中包含数字和单词-我是从字典里查出来的( matches )那已经 int string 价值观。我想得到一个数组或者我可以循环使用的东西,它只包含数字,按数字排序,然后在控制台中显示它们。

    通过使用正则表达式,我可以很容易地对单个字符串执行此操作,但是当我有一个字符串数组时,我不知道如何执行此操作。

    var matches = new Dictionary<int, string>();
    matches.Add(1, "value1");
    matches.Add(2, "value5");
    matches.Add(3, "value2");
    var items = matches.Values.ToArray();
    Array.Sort(items, StringComparer.CurrentCulture);
    Regex rgx = new Regex(@"\D");
    rgx.Replace(items, ""); //This doesn't work with arrays!
    int[] numbers = Array.ConvertAll(items, s => int.Parse(s)); //This doesn't work because my strings still contain letters
    foreach (int c in numbers)
    {
        Console.WriteLine(string.Format("Number is {0}", c));
        Console.ReadKey();
    }
    

    期望输出为:

    Number is 1
    Number is 5
    Number is 2
    

    如果不明显,这些数字来自 value1 value5 value2 .

    3 回复  |  直到 6 年前
        1
  •  4
  •   dymanoid    6 年前

    您可以使用LINQ来完成。该表达式具有很强的声明性和自我解释性:

    // we're searching for digits, not removing non-digits as in your example
    Regex regex = new Regex(@"\d+");
    
    var results = matches.Values
        .Select(v => regex.Match(v))     // do regex on each item
        .Where(m => m.Success)           // select only those results where regex worked
        .Select(m => int.Parse(m.Value)) // convert to int
        .ToList();                       // convert the results to a list - if you want to sort it
    
    // you wanted to sort the list, right?
    results.Sort();
    
    foreach (int number in results)
    {
        Console.WriteLine($"Number is {number}");
    }
    
        2
  •  0
  •   Falco Alexander    6 年前

    List<T> 而不是阵列将使事情变得更容易!

    var matches = new Dictionary<int, string>();
    matches.Add(1, "value1");
    matches.Add(2, "value5");
    matches.Add(3, "value2");
    
    var items = matches.Values.ToList();
    items.Sort( StringComparer.CurrentCulture);
    Regex rgx = new Regex(@"\D");
    var numbers = items.Select(i => int.Parse(rgx.Replace(i, "")));
    
    foreach (int c in numbers)
    {
        Console.WriteLine(string.Format($"Number is {c}"));
    }
    
        3
  •  0
  •   jdweng    6 年前

    下面是一个使用正则表达式的示例:

                string[] input = { "Number is 1", "Number is 5", "Number is 2" };
                string pattern = @"\d+";
    
                int[] results = input.Select(x => Regex.Match(x, pattern)).Cast<Match>().Select(x => int.Parse(x.Value)).ToArray();