Get multiple numbers from a string

后端 未结 3 1912
轻奢々
轻奢々 2021-01-23 16:40

I have strings like

AS_!SD 2453iur ks@d9304-52kasd

I need to get the 2 frist numbres of the string:

for that case will be:

3条回答
  •  攒了一身酷
    2021-01-23 17:20

    This solution will take two first numbers, each can have any number of digits

    string s =  "AS_!SD 2453iur ks@d9304-52kasd";
    
    MatchCollection matches = Regex.Matches(s, @"\d+");
    
    string[] result = matches.Cast()
                             .Take(2)
                             .Select(match => match.Value)
                             .ToArray();
    
    Console.WriteLine( string.Join(Environment.NewLine, result) );
    

    will print

    2453
    9304
    

    you can parse them to int[] by result.Select(int.Parse).ToArray();

提交回复
热议问题