Extract multiple integers from string and store as int

前端 未结 3 1204
無奈伤痛
無奈伤痛 2021-01-24 02:20

I know that this will extract the number and store as int -

string inputData = \"sometex10\";

string  data = System.Text.RegularExpressions.Regex.Match(inputDa         


        
相关标签:
3条回答
  • 2021-01-24 02:27
    C# program that uses Regex.Split
    

    Referencing : http://www.dotnetperls.com/regex-split

    using System;
    using System.Text.RegularExpressions;
    
    class Program
    {
        static void Main()
        {
        //
        // String containing numbers.
        //
        string sentence = "10 cats, 20 dogs, 40 fish and 1 programmer.";
        //
        // Get all digit sequence as strings.
        //
        string[] digits = Regex.Split(sentence, @"\D+");
        //
        // Now we have each number string.
        //
        foreach (string value in digits)
        {
            //
            // Parse the value to get the number.
            //
            int number;
            if (int.TryParse(value, out number))
            {
                 Console.WriteLine(number);
            }
        }
        }
    }
    
    0 讨论(0)
  • 2021-01-24 02:32

    You can use a LINQ one-liner:

    var numbers = Regex.Matches(inputData, @"\d+").Select(m => int.Parse(m.Value)).ToList();
    

    Or use ToArray() if you prefer an array instead of a list.

    0 讨论(0)
  • 2021-01-24 02:48

    You can use something like this:

    string inputData = "sometex10";
    List<int> numbers = new List<int>();
    foreach(Match m in Regex.Matches(inputData, @"\d+"))
    {
        numbers.Add(Convert.ToInt32(m.Value));
    }
    

    This will store the integers in the list numbers

    0 讨论(0)
提交回复
热议问题