简体   繁体   中英

How get numbers from string (C#)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM