Find and extract a number from a string

前端 未结 29 2625
温柔的废话
温柔的废话 2020-11-22 03:19

I have a requirement to find and extract a number contained within a string.

For example, from these strings:

string test = \"1 test\"
string test1 =         


        
29条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 03:55

    Regex.Split can extract numbers from strings. You get all the numbers that are found in a string.

    string input = "There are 4 numbers in this string: 40, 30, and 10.";
    // Split on one or more non-digit characters.
    string[] numbers = Regex.Split(input, @"\D+");
    foreach (string value in numbers)
    {
        if (!string.IsNullOrEmpty(value))
        {
        int i = int.Parse(value);
        Console.WriteLine("Number: {0}", i);
        }
    }
    

    Output:

    Number: 4 Number: 40 Number: 30 Number: 10

提交回复
热议问题