从字符串中获取特定数字

本文关键字:数字 获取 字符串 | 更新日期: 2023-09-27 18:33:14

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

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

我想拿出第一个号码集或第二个号码集。因此,如果我要求数字集 1,我将得到 12 作为回报,如果我要求数字集 2,我将得到 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();
    }
}

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

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

看起来很

适合Regex.

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

您将循环访问从Regex.Matches返回的Matches集合,并依次分析每个返回的匹配项。

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

你可以使用正则表达式:

Regex regex = new Regex(@"^[0-9]+$");
您可以使用

字符串将字符串分成几部分。拆分,然后使用 foreach 应用 int 遍历列表。TryParse,像这样:

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);
}

现在数字有有效值的列表