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

例如,从这些字符串:

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

我该怎么做呢?


当前回答

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

其他回答

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

PS C:\> $str = '1 test'
PS C:\> [regex]::match($str,'\d+').value
1

Ahmad Mageed在这里提供了一种有趣的方法,使用Regex和StringBuilder以它们在字符串中出现的顺序提取整数。

一个使用Regex的例子。根据艾哈迈德·马吉德的帖子,下文如下:

var dateText = "MARCH-14-Tue";
string splitPattern = @"[^\d]";
string[] result = Regex.Split(dateText, splitPattern);
var finalresult = string.Join("", result.Where(e => !String.IsNullOrEmpty(e)));
int DayDateInt = 0;

int.TryParse(finalresult, out DayDateInt);

我用什么来得到电话号码没有任何标点符号…

var phone = "(787) 763-6511";

string.Join("", phone.ToCharArray().Where(Char.IsDigit));

// result: 7877636511
var outputString = String.Join("", inputString.Where(Char.IsDigit));

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

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

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

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