从字符串中获取具体数字

5
在我的当前项目中,我需要大量使用子字符串,并想知道是否有更简单的方法从字符串中获取数字。
例如: 我有一个像这样的字符串: 12 text text 7 text
我想要能够获取第一个数字集或第二个数字集。 因此,如果我请求数字集1,我将得到12作为返回值,如果我请求数字集2,我将得到7作为返回值。
谢谢!
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();
    }
}

谢谢,正是我所需要的!:D 顺便说一下,抱歉给你投了反对票,因为我不知道我作为新注册用户不能投票。 - Tobias Lindberg
那我很好奇为什么有人会对这个答案点踩。不管怎样,你还是很受欢迎的 :) - Paolo Tedesco
PaoloTedesco:我想那是我。很困惑,因为一开始它说我太新了无法点赞,然后变成了踩。不管怎样,你现在得到了一个赞 :D - Tobias Lindberg
我遇到了一个错误:我已经添加了 System.Core.dll,但是我得到了 找不到“Cast”查询表达式模式的实现。您是否缺少“System.Linq”使用指令或“System.Core.dll”程序集引用?(CS1935) (atest) 的错误提示。 - Jack
1
@Jack:你尝试过错误信息建议的做法了吗,即添加对 System.Core.dll 的引用(如果您复制了示例,则应该有“using System.Linq”)? - Paolo Tedesco
显示剩余4条评论

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

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


1

看起来正则表达式是个不错的选择。

基本的正则表达式应该是\d+,用于匹配(一个或多个数字)。

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

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

foreach(var match in matches)
{
    myIntList.Add(int.Parse(match.Value));
}

0

您可以使用string.Split将字符串分割成部分,然后使用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);
}

现在 numbers 具有有效值列表。


嗨Oded,感谢你的指正。正如第一句所提到的,应该是TryParse。我已经更正了它。 - user694833

0
你可以使用正则表达式:
Regex regex = new Regex(@"^[0-9]+$");

您假定前导 0 不被允许。 - Oded

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接