我需要找到并提取字符串中包含的数字。
例如,从这些字符串:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
我该怎么做呢?
我需要找到并提取字符串中包含的数字。
例如,从这些字符串:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
我该怎么做呢?
当前回答
另一个使用Regex的简单解决方案 你应该使用这个
using System.Text.RegularExpressions;
代码是
string var = "Hello3453232wor705Ld";
string mystr = Regex.Replace(var, @"\d", "");
string mynumber = Regex.Replace(var, @"\D", "");
Console.WriteLine(mystr);
Console.WriteLine(mynumber);
其他回答
下面是另一个使用Linq的简单解决方案,它只从字符串中提取数值。
var numbers = string.Concat(stringInput.Where(char.IsNumber));
例子:
var numbers = string.Concat("(787) 763-6511".Where(char.IsNumber));
了:“7877636511”
这是我的算法
//Fast, C Language friendly
public static int GetNumber(string Text)
{
int val = 0;
for(int i = 0; i < Text.Length; i++)
{
char c = Text[i];
if (c >= '0' && c <= '9')
{
val *= 10;
//(ASCII code reference)
val += c - 48;
}
}
return val;
}
你必须使用Regex作为\d+
\d匹配给定字符串中的数字。
我使用这个一行程序从任何字符串中提取所有数字。
var phoneNumber = "(555)123-4567";
var numsOnly = string.Join("", new Regex("[0-9]").Matches(phoneNumber)); // 5551234567
有一个问题的答案正好相反: 如何使用Regex.Replace从字符串中删除数字?
// Pull out only the numbers from the string using LINQ
var numbersFromString = new String(input.Where(x => x >= '0' && x <= '9').ToArray());
var numericVal = Int32.Parse(numbersFromString);