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

例如,从这些字符串:

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

我该怎么做呢?


当前回答

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

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

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

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

其他回答

我使用这个一行程序从任何字符串中提取所有数字。

var phoneNumber = "(555)123-4567";
var numsOnly = string.Join("", new Regex("[0-9]").Matches(phoneNumber)); // 5551234567

下面是另一种Linq方法,它从字符串中提取第一个数字。

string input = "123 foo 456";
int result = 0;
bool success = int.TryParse(new string(input
                     .SkipWhile(x => !char.IsDigit(x))
                     .TakeWhile(x => char.IsDigit(x))
                     .ToArray()), out result);

例子:

string input = "123 foo 456"; // 123
string input = "foo 456";     // 456
string input = "123 foo";     // 123

你必须使用Regex作为\d+

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

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

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

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