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

时间:2019-01-11 11:51:39

标签: c# regex

我有一个包含数字和单词的字符串(items)数组-我是从具有matches和{{1 }}中的值。我想得到一个数组或一个我可以遍历的东西,它只包含数字,按数字排序,然后在控制台中显示它们。

通过使用正则表达式,我可以轻松地对单个字符串执行此操作,但是当我有一个字符串数组时,我不知道该怎么做。

下面的代码,请参阅注释:

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

3 个答案:

答案 0 :(得分:4)

您可以使用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}");
}

答案 1 :(得分:0)

使用List<T>而不是Array可以使事情变得更加容易!

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

答案 2 :(得分:0)

以下是使用Regex的示例:

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