我需要找到并提取字符串中包含的数字。
例如,从这些字符串:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
我该怎么做呢?
我需要找到并提取字符串中包含的数字。
例如,从这些字符串:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
我该怎么做呢?
当前回答
下面是另一个使用Linq的简单解决方案,它只从字符串中提取数值。
var numbers = string.Concat(stringInput.Where(char.IsNumber));
例子:
var numbers = string.Concat("(787) 763-6511".Where(char.IsNumber));
了:“7877636511”
其他回答
string verificationCode ="dmdsnjds5344gfgk65585";
string code = "";
Regex r1 = new Regex("\\d+");
Match m1 = r1.Match(verificationCode);
while (m1.Success)
{
code += m1.Value;
m1 = m1.NextMatch();
}
var outputString = String.Join("", inputString.Where(Char.IsDigit));
获取字符串中的所有数字。 所以如果你用“1 + 2”这个例子,它会得到“12”。
var match=Regex.Match(@"a99b",@"\d+");
if(match.Success)
{
int val;
if(int.TryParse(match.Value,out val))
{
//val is set
}
}
你必须使用Regex作为\d+
\d匹配给定字符串中的数字。
你可以像下面这样使用String属性:
return new String(input.Where(Char.IsDigit).ToArray());
它只给出字符串中的数字。