我需要找到并提取字符串中包含的数字。
例如,从这些字符串:
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
其他回答
只需使用一个RegEx来匹配字符串,然后转换:
Match match = Regex.Match(test , @"(\d+)");
if (match.Success) {
return int.Parse(match.Groups[1].Value);
}
有一个问题的答案正好相反: 如何使用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());
这个问题并没有明确地说明您只是想要字符0到9,但从您的示例集和注释中相信这是正确的并不过分。这是做这个的代码。
string digitsOnly = String.Empty;
foreach (char c in s)
{
// Do not use IsDigit as it will include more than the characters 0 through to 9
if (c >= '0' && c <= '9') digitsOnly += c;
}
为什么不想使用Char.IsDigit()——数字包括分数、下标、上标、罗马数字、货币分子、围起来的数字和特定于脚本的数字。
var outputString = String.Join("", inputString.Where(Char.IsDigit));
获取字符串中的所有数字。 所以如果你用“1 + 2”这个例子,它会得到“12”。