【问题标题】:Get specific numbers from string从字符串中获取特定数字
【发布时间】:2012-05-05 18:44:54
【问题描述】:

在我当前的项目中,我必须大量使用子字符串,我想知道是否有更简单的方法可以从字符串中取出数字。

示例: 我有一个这样的字符串: 12文字文字7文字

我希望能够获得第一个号码组或第二个号码组。 因此,如果我要求数字集 1,我将得到 12 作为回报,如果我要求数字集 2,我将得到 7 作为回报。

谢谢!

【问题讨论】:

    标签: c# string split


    【解决方案1】:

    这将从字符串创建一个整数数组:

    using System.Linq;
    using System.Text.RegularExpressions;
    
    class Program {
        static void Main() {
            string text = "12 text text 7 text";
            int[] numbers = (from Match m in Regex.Matches(text, @"\d+") select int.Parse(m.Value)).ToArray();
        }
    }
    

    【讨论】:

    • 谢谢,正是我需要的! :D 顺便说一句,很抱歉投了反对票,不知道我不能投票,因为我是新注册的。
    • @TobiasLindberg:很高兴它有帮助,在这种情况下,您可以撤消对 meybe 的反对票 :)?
    • 对不起,这只是客户端的事情,它实际上并没有对你投反对票。再次感谢!
    • 那么我很想知道为什么有人反对这个答案。无论如何,不​​客气:)
    • @Jack:你有没有尝试过错误消息的建议,即添加对 System.Core.dll 的引用(如果你复制了示例,我想using System.Linq 在那里)
    【解决方案2】:

    尝试使用正则表达式,您可以匹配[0-9]+,它将匹配字符串中的任何数字。使用这个正则表达式的C#代码大致如下:

    Match match = Regex.Match(input, "[0-9]+", RegexOptions.IgnoreCase);
    
    // Here we check the Match instance.
    if (match.Success)
    {
        // here you get the first match
        string value = match.Groups[1].Value;
    }
    

    当然,您仍然需要解析返回的字符串。

    【讨论】:

      【解决方案3】:

      看起来很适合Regex。

      基本正则表达式将是\d+ 以匹配(一位或多位数字)。

      您将遍历从Regex.Matches 返回的Matches 集合,并依次解析每个返回的匹配项。

      var matches = Regex.Matches(input, "\d+");
      
      foreach(var match in matches)
      {
          myIntList.Add(int.Parse(match.Value));
      }
      

      【讨论】:

        【解决方案4】:

        你可以使用正则表达式:

        Regex regex = new Regex(@"^[0-9]+$");
        

        【讨论】:

        • 你假设前导0s 是不允许的。
        【解决方案5】:

        您可以使用 string.Split 将字符串拆分为多个部分,然后使用应用 int.TryParse 的 foreach 遍历列表,如下所示:

        string test = "12 text text 7 text";
        var numbers = new List<int>();
        int i;
        foreach (string s in test.Split(' '))
        {
             if (int.TryParse(s, out i)) numbers.Add(i);
        }
        

        现在 numbers 有有效值列表

        【讨论】:

        • 嗨,Oded,感谢您的关注。如第一句所说,应该是TryParse。我已经更正了。
        猜你喜欢
        • 1970-01-01
        • 2013-11-20
        • 2017-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多