5

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

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

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

谢谢!

4

5 回答 5

7

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

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();
    }
}
于 2012-05-05T18:51:45.777 回答
1

看起来很适合Regex.

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

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

var matches = Regex.Matches(input, "\d+");

foreach(var match in matches)
{
    myIntList.Add(int.Parse(match.Value));
}
于 2012-05-05T18:47:30.547 回答
1

尝试使用正则表达式,您可以匹配[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;
}

当然,您仍然必须解析返回的字符串。

于 2012-05-05T18:47:40.973 回答
0

你可以使用正则表达式:

Regex regex = new Regex(@"^[0-9]+$");
于 2012-05-05T18:49:03.017 回答
0

您可以使用 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 有有效值的列表

于 2012-05-05T18:52:39.310 回答