我需要找到并提取字符串中包含的数字。
例如,从这些字符串:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
我该怎么做呢?
我需要找到并提取字符串中包含的数字。
例如,从这些字符串:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
我该怎么做呢?
当前回答
string input = "Hello 20, I am 30 and he is 40";
var numbers = Regex.Matches(input, @"\d+").OfType<Match>().Select(m => int.Parse(m.Value)).ToArray();
其他回答
正则表达式。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在两行:
decimal result = 0;
decimal.TryParse(Regex.Match(s, @"\d+").Value, out result);
同样的事情也适用于float, long等等…
你可以像下面这样使用String属性:
return new String(input.Where(Char.IsDigit).ToArray());
它只给出字符串中的数字。
我使用这个一行程序从任何字符串中提取所有数字。
var phoneNumber = "(555)123-4567";
var numsOnly = string.Join("", new Regex("[0-9]").Matches(phoneNumber)); // 5551234567
string verificationCode ="dmdsnjds5344gfgk65585";
string code = "";
Regex r1 = new Regex("\\d+");
Match m1 = r1.Match(verificationCode);
while (m1.Success)
{
code += m1.Value;
m1 = m1.NextMatch();
}