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

例如,从这些字符串:

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

我该怎么做呢?


当前回答

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

其他回答

你必须使用Regex作为\d+

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

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

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

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

遍历字符串并使用Char。IsDigit

string a = "str123";
string b = string.Empty;
int val;

for (int i=0; i< a.Length; i++)
{
    if (Char.IsDigit(a[i]))
        b += a[i];
}

if (b.Length>0)
    val = int.Parse(b);

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 outputString = String.Join("", inputString.Where(Char.IsDigit));

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