我需要找到并提取字符串中包含的数字。

例如,从这些字符串:

string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"

我该怎么做呢?


当前回答

正则表达式。Split可以从字符串中提取数字。你会得到在字符串中找到的所有数字。

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

输出:

数量:4 数量:40 数量:30 数量:10

其他回答

var match=Regex.Match(@"a99b",@"\d+");
if(match.Success)
{
    int val;
    if(int.TryParse(match.Value,out val))
    {
        //val is set
    }
}

这个问题并没有明确地说明您只是想要字符0到9,但从您的示例集和注释中相信这是正确的并不过分。这是做这个的代码。

        string digitsOnly = String.Empty;
        foreach (char c in s)
        {
            // Do not use IsDigit as it will include more than the characters 0 through to 9
            if (c >= '0' && c <= '9') digitsOnly += c;
        }

为什么不想使用Char.IsDigit()——数字包括分数、下标、上标、罗马数字、货币分子、围起来的数字和特定于脚本的数字。

你也可以试试这个

string.Join(null,System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]"));

这是我的解决方案

string var = "Hello345wor705Ld";
string alpha = string.Empty;
string numer = string.Empty;
foreach (char str in var)
{
    if (char.IsDigit(str))
        numer += str.ToString();
    else
        alpha += str.ToString();
}
Console.WriteLine("String is: " + alpha);
Console.WriteLine("Numeric character is: " + numer);
Console.Read();

Ahmad Mageed在这里提供了一种有趣的方法,使用Regex和StringBuilder以它们在字符串中出现的顺序提取整数。

一个使用Regex的例子。根据艾哈迈德·马吉德的帖子,下文如下:

var dateText = "MARCH-14-Tue";
string splitPattern = @"[^\d]";
string[] result = Regex.Split(dateText, splitPattern);
var finalresult = string.Join("", result.Where(e => !String.IsNullOrEmpty(e)));
int DayDateInt = 0;

int.TryParse(finalresult, out DayDateInt);