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

例如,从这些字符串:

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

我该怎么做呢?


当前回答

你也可以试试这个

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

其他回答

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

你也可以试试这个

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

使用上面的@tim-pietzcker回答,以下将适用于PowerShell。

PS C:\> $str = '1 test'
PS C:\> [regex]::match($str,'\d+').value
1
var outputString = String.Join("", inputString.Where(Char.IsDigit));

获取字符串中的所有数字。 所以如果你用“1 + 2”这个例子,它会得到“12”。

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