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

例如,从这些字符串:

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

我该怎么做呢?


当前回答

这个问题并没有明确地说明您只是想要字符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()——数字包括分数、下标、上标、罗马数字、货币分子、围起来的数字和特定于脚本的数字。

其他回答

这个问题并没有明确地说明您只是想要字符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]"));

正则表达式。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

 string input = "Hello 20, I am 30 and he is 40";
 var numbers = Regex.Matches(input, @"\d+").OfType<Match>().Select(m => int.Parse(m.Value)).ToArray();

基于上一个示例,我创建了一个方法:

private string GetNumberFromString(string sLongString, int iLimitNumbers)
{
    string sReturn = "NA";
    int iNumbersCounter = 0;
    int iCharCounter = 0; 

    string sAlphaChars = string.Empty;
    string sNumbers = string.Empty;
    foreach (char str in sLongString)
    {
        if (char.IsDigit(str))
        {
            sNumbers += str.ToString();
            iNumbersCounter++;
            if (iNumbersCounter == iLimitNumbers)
            {
                return sReturn = sNumbers;
            }
        }
        else
        {
            sAlphaChars += str.ToString();
            iCharCounter++;
            // reset the counter 
            iNumbersCounter = 0; 
        }
    }
    return sReturn;
}