NET问答: 如何从 string 中挖出所有的 number ?

咨询区

  • van:

我现在有一个需求,想从 string 中找到所有的 number 并提取出来。

举例如下:


string test = "1 hello"
string test1 = " 1 world"
string test2 = "helloworld 99"

请问我该如何做?

回答区

  • Tabares:

这个简单,可以用正则表达式 Regex.Split 提取所有的 number,使用下面的代码。


    public class Program
    {
        static void Main(string[] args)
        {
            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);
                }
            }
        }
    }


  • Ramireddy Ambati:

可以试着用 Regex.Matches 提取。


        static void Main(string[] args)
        {
            string input = "Hello 20, I am 30 and he is 40";

            var numbers = Regex.Matches(input, @"\d+").OfType<Match>().Select(m => int.Parse(m.Value)).ToArray();

            foreach (var item in numbers)
            {
                Console.WriteLine($"number: {item}");
            }
        }


  • Thomas C. G. de Vilhena:

我写了一个扩展方法可以提取出 string 中所有的正整数,方法如下:


    public static class StringExt
    {
        public static List<longNumbers(this string str)
        {
            var nums = new List<long>();
            var start = -1;
            for (int i = 0; i < str.Length; i++)
            {
                if (start < 0 && Char.IsDigit(str[i]))
                {
                    start = i;
                }
                else if (start >= 0 && !Char.IsDigit(str[i]))
                {
                    nums.Add(long.Parse(str.Substring(start, i - start)));
                    start = -1;
                }
            }
            if (start >= 0)
                nums.Add(long.Parse(str.Substring(start, str.Length - start)));
            return nums;
        }
    }

然后像下面这样调用

        public static void Main(string[] args)
        {
            var input = "I was born in 1989, 27 years ago from now (2016)";

            foreach (var item in input.Numbers())
            {
                Console.WriteLine($"number: {item}");
            }
        }

点评区

从解答中再次看到了 正则 的强大威力,不得不服,不过这种需求可以简单,也可以特别复杂,比如考虑下面的情况:

  • 小数      eg: 200.002,100.01
  • 负数      eg: -20.02,-10.0

当然都可以用相对复杂的正则写出来,但现实中不得不考虑这些情况哈😂😂😂

原文链接:https://stackoverflow.com/questions/4734116/find-and-extract-a-number-from-a-string


本文分享自微信公众号 - 一线码农聊技术(dotnetfly)。
如有侵权,请联系 [email protected] 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章