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

例如,从这些字符串:

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

我该怎么做呢?


当前回答

只需使用一个RegEx来匹配字符串,然后转换:

Match match = Regex.Match(test , @"(\d+)");
if (match.Success) {
   return int.Parse(match.Groups[1].Value);
}

其他回答

你必须使用Regex作为\d+

\d匹配给定字符串中的数字。

使用StringBuilder比在循环中连接字符串的性能稍好一些。如果处理的是大字符串,它的性能要高得多。

    public static string getOnlyNumbers(string input)
    {
        StringBuilder stringBuilder = new StringBuilder(input.Length);
        for (int i = 0; i < input.Length; i++)
            if (input[i] >= '0' && input[i] <= '9')
                stringBuilder.Append(input[i]);

        return stringBuilder.ToString();
    }

注意:上面的例子函数只适用于正数

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

对于那些想要十进制数字的字符串与Regex在两行:

decimal result = 0;
decimal.TryParse(Regex.Match(s, @"\d+").Value, out result);

同样的事情也适用于float, long等等…

有一个问题的答案正好相反: 如何使用Regex.Replace从字符串中删除数字?

// Pull out only the numbers from the string using LINQ

var numbersFromString = new String(input.Where(x => x >= '0' && x <= '9').ToArray());

var numericVal = Int32.Parse(numbersFromString);