我需要找到并提取字符串中包含的数字。
例如,从这些字符串:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
我该怎么做呢?
我需要找到并提取字符串中包含的数字。
例如,从这些字符串:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
我该怎么做呢?
当前回答
正则表达式。Split可以从字符串中提取数字。你会得到在字符串中找到的所有数字。
string input = "There are 4 numbers in this string: 40, 30, and 10.";
// Split on one or more non-digit characters.
string[] numbers = Regex.Split(input, @"\D+");
foreach (string value in numbers)
{
if (!string.IsNullOrEmpty(value))
{
int i = int.Parse(value);
Console.WriteLine("Number: {0}", i);
}
}
输出:
数量:4 数量:40 数量:30 数量:10
其他回答
这是我的解决方案
string var = "Hello345wor705Ld";
string alpha = string.Empty;
string numer = string.Empty;
foreach (char str in var)
{
if (char.IsDigit(str))
numer += str.ToString();
else
alpha += str.ToString();
}
Console.WriteLine("String is: " + alpha);
Console.WriteLine("Numeric character is: " + numer);
Console.Read();
\d+是整数的正则表达式。所以
//System.Text.RegularExpressions.Regex
resultString = Regex.Match(subjectString, @"\d+").Value;
返回subjectString中第一个数字出现的字符串。
Int32.Parse(resultString)会给你一个数字。
下面是另一种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
var outputString = String.Join("", inputString.Where(Char.IsDigit));
获取字符串中的所有数字。 所以如果你用“1 + 2”这个例子,它会得到“12”。
以下是我如何清理电话号码,让它只有数字:
string numericPhone = new String(phone.Where(Char.IsDigit).ToArray());