我需要找到并提取字符串中包含的数字。
例如,从这些字符串:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
我该怎么做呢?
我需要找到并提取字符串中包含的数字。
例如,从这些字符串:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
我该怎么做呢?
当前回答
使用上面的@tim-pietzcker回答,以下将适用于PowerShell。
PS C:\> $str = '1 test'
PS C:\> [regex]::match($str,'\d+').value
1
其他回答
有一个问题的答案正好相反: 如何使用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);
以下是我如何清理电话号码,让它只有数字:
string numericPhone = new String(phone.Where(Char.IsDigit).ToArray());
\d+是整数的正则表达式。所以
//System.Text.RegularExpressions.Regex
resultString = Regex.Match(subjectString, @"\d+").Value;
返回subjectString中第一个数字出现的字符串。
Int32.Parse(resultString)会给你一个数字。
string verificationCode ="dmdsnjds5344gfgk65585";
string code = "";
Regex r1 = new Regex("\\d+");
Match m1 = r1.Match(verificationCode);
while (m1.Success)
{
code += m1.Value;
m1 = m1.NextMatch();
}
下面是另一个使用Linq的简单解决方案,它只从字符串中提取数值。
var numbers = string.Concat(stringInput.Where(char.IsNumber));
例子:
var numbers = string.Concat("(787) 763-6511".Where(char.IsNumber));
了:“7877636511”