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

例如,从这些字符串:

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

我该怎么做呢?


当前回答

你也可以试试这个

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

其他回答

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

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

这是我的算法

    //Fast, C Language friendly
    public static int GetNumber(string Text)
    {
        int val = 0;
        for(int i = 0; i < Text.Length; i++)
        {
            char c = Text[i];
            if (c >= '0' && c <= '9')
            {
                val *= 10;
                //(ASCII code reference)
                val += c - 48;
            }
        }
        return val;
    }

下面是Linq版本:

string s = "123iuow45ss";
var getNumbers = (from t in s
                  where char.IsDigit(t)
                  select t).ToArray();
Console.WriteLine(new string(getNumbers));

使用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();
    }

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

  string verificationCode ="dmdsnjds5344gfgk65585";
            string code = "";
            Regex r1 = new Regex("\\d+");
          Match m1 = r1.Match(verificationCode);
           while (m1.Success)
            {
                code += m1.Value;
                m1 = m1.NextMatch();
            }