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

例如,从这些字符串:

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

其他回答

\d+是整数的正则表达式。所以

//System.Text.RegularExpressions.Regex
resultString = Regex.Match(subjectString, @"\d+").Value;

返回subjectString中第一个数字出现的字符串。

Int32.Parse(resultString)会给你一个数字。

你也可以试试这个

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

以下是我如何清理电话号码,让它只有数字:

string numericPhone = new String(phone.Where(Char.IsDigit).ToArray());

正则表达式。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 s = "kg g L000145.50\r\n";
        char theCharacter = '.';
        var getNumbers = (from t in s
                          where char.IsDigit(t) || t.Equals(theCharacter)
                          select t).ToArray();
        var _str = string.Empty;
        foreach (var item in getNumbers)
        {
            _str += item.ToString();
        }
        double _dou = Convert.ToDouble(_str);
        MessageBox.Show(_dou.ToString("#,##0.00"));