如何从字符串中获取数字(C#)

时间:2023-02-05 19:44:33

I have the following string:

我有以下字符串:

{ (MerchantId eq 5 or MerchantId eq 19 or MerchantId eq 34)}

I need to get as result an array of numbers:

我需要得到一组数字:

5

19

34

I can't find the necessary regex expression for this action. Thanks for help in advance.

我无法为此操作找到必要的正则表达式。提前感谢您的帮助。

1 个解决方案

#1


0  

Here you go:

干得好:

string input = "{ (MerchantId eq 5 or MerchantId eq 19 or MerchantId eq 34)}";
Regex regex = new Regex(@"(\d+)");
List<int> numbers = new List<int>();

var matches = regex.Matches(input);

for (int i = 0; i < matches.Count; i++)
{
    numbers.Add(Int32.Parse(matches[i].Value));
}

If you insist on arrays use this instead:

如果你坚持使用数组,请改用:

var matches = regex.Matches(input);
int[] numbers = new int[matches.Count];

for (int i = 0; i < matches.Count; i++)
{
    numbers[i] = Int32.Parse(matches[i].Value);
}

#1


0  

Here you go:

干得好:

string input = "{ (MerchantId eq 5 or MerchantId eq 19 or MerchantId eq 34)}";
Regex regex = new Regex(@"(\d+)");
List<int> numbers = new List<int>();

var matches = regex.Matches(input);

for (int i = 0; i < matches.Count; i++)
{
    numbers.Add(Int32.Parse(matches[i].Value));
}

If you insist on arrays use this instead:

如果你坚持使用数组,请改用:

var matches = regex.Matches(input);
int[] numbers = new int[matches.Count];

for (int i = 0; i < matches.Count; i++)
{
    numbers[i] = Int32.Parse(matches[i].Value);
}